public EventHandlerWrapper(IBuildProvider provider, object self, DynamicFunction f, string virtualPath) { _self = self; _f = f; _virtualPath = virtualPath; _provider = provider; }
private object Function(Token token) { var name = token.Ident.Value; if (functions.ContainsKey(name)) { throw new ArgumentException("Name was used"); } if (variables.ContainsKey(name)) { throw new ArgumentException("Name was used"); } var paramCheckList = new List <string>(); foreach (var item in token.Params) { var param = item.Value; if (paramCheckList.Contains(param)) { throw new Exception("Parameter name was already used"); } paramCheckList.Add(param); } var func = new DynamicFunction() { Context = this, Name = name, Params = token.Params, Block = token.Block, }; functions[name] = func; return(null); }
private void HookupScriptHandlers() { // This is done once per HttpApplication/HttpModule instance every time // a global.<ext> file changes // If it's the first request in the domain, call Application_OnStart (if any) if (s_firstRequest && s_buildResult != null) { s_buildResult.CallOnStartMethod(); } // Hook up all the events implemented in the 'global' file foreach (string handlerName in _handlers.Keys) { EventHandlerWrapper eventHandlerWrapper = _handlers[handlerName]; DynamicFunction f = null; if (s_buildResult != null && s_buildResult.EventHandlers != null) { s_buildResult.EventHandlers.TryGetValue(handlerName, out f); } eventHandlerWrapper.SetDynamicFunction(f, s_globalVirtualPath); } }
internal void HookupHandler(IBuildProvider provider, ScriptScope moduleGlobals, object self, object target) { DynamicFunction scriptFunction = new DynamicFunction((object)moduleGlobals.GetVariable(_handlerName)); Delegate handler = EventHandlerWrapper.GetWrapper( provider, self, scriptFunction, _scriptVirtualPath, typeof(EventHandler)); _eventInfo.AddEventHandler(target, handler); }
public object CallDataBindingFunction(object dataItem, DynamicFunction f, params object[] args) { // We need to inject the data item in the globals dictionary to make it available SetDataItem(dataItem); try { return(CallFunction(f, args)); } finally { ClearDataItem(); } }
public void TestPyDynamicCS() { var meth = DynamicFunction.CreateFunction("SquareX", "public static double SquareX(double x){return x * x;}", null, null, null); var sig = DynamicFunction.MethodSignature(meth); Assert.AreEqual(sig, "Double->Double"); var result = DynamicFunction.RunFunctionRedirectOutput(meth, new object[] { (double)3 }); Assert.AreEqual(result.Item1, 9.0); }
public void TestStorageMethodInfo() { var meth = DynamicFunction.CreateFunction("SquareX", "public static double SquareX(double x){return x * x;}", null, null, null); double x = 3.456; double y = (double)meth.Invoke(null, new object[] { x }); var i = ObjectStorage.Inst.AddIncref(meth); var fct = ObjectStorage.Inst.Get(i).MethodInfo; double y2 = (double)fct.Invoke(null, new object[] { x }); Assert.AreEqual(y, y2); }
internal static EventHookupHelper Create(Type type, string eventName, string handlerName, DynamicFunction f, string scriptVirtualPath) { EventInfo eventInfo = GetEventInfo(type, eventName, f, scriptVirtualPath); if (eventInfo == null) { return(null); } return(new EventHookupHelper(handlerName, eventInfo, scriptVirtualPath)); }
// Call a method internal static object CallMethod(ScriptEngine engine, DynamicFunction f, string defaultVirtualPath, params object[] args) { try { return(f.Invoke(engine, args)); } catch (Exception e) { if (!ProcessRuntimeException(engine, e, defaultVirtualPath)) { throw; } } return(null); }
public void TestPyDynamicCSFails() { try { DynamicFunction.CreateFunction("SquareX", "public static double SquareX(double x){return x * y;}", null, null, null); } catch (Exception e) { var s = e.ToString(); Assert.IsTrue(s.Contains("'y'")); } }
internal static EventInfo GetEventInfo(Type type, string eventName, DynamicFunction f, string scriptVirtualPath) { EventInfo eventInfo = type.GetEvent(eventName); // If it doesn't match an event name, just ignore it if (eventInfo == null) { return(null); } return(eventInfo); }
public static Delegate GetWrapper(IBuildProvider provider, DynamicFunction f, string virtualPath, Type delegateType) { // Get the MethodInfo only once if (_handlerMethodInfo == null) { _handlerMethodInfo = typeof(EventHandlerWrapper).GetMethod("Handler"); } EventHandlerWrapper wrapper = new EventHandlerWrapper(provider, f, virtualPath); // Create a delegate of the required type return(Delegate.CreateDelegate(delegateType, wrapper, _handlerMethodInfo)); }
internal void SetProperty(string propertyName, object value) { // Try to get a dynamic setter for this property DynamicFunction setterFunction = GetPropertySetter(propertyName); // If we couldn't find a setter, just set a field by that name if (setterFunction == null) { _scope.SetVariable(propertyName, value); return; } // Set the property value CallFunction(setterFunction, value); }
private void InitMethodsInternal(Type type, ScriptScope moduleGlobals) { // If CompiledCode is null, there was no script to compile if (CompiledCode == null) { return; } foreach (KeyValuePair <string, object> pair in moduleGlobals.GetItems()) { // Wrap it as a dynamic object. It may not be something callable, and if it's not, // it will fail when we try to call it. DynamicFunction f = new DynamicFunction(pair.Value); ProcessEventHandler(pair.Key, type, f); } }
private void CallFunction(ScriptEngine engine, DynamicFunction f) { if (f == null) { return; } try { f.Invoke(engine); } catch (Exception e) { if (!EngineHelper.ProcessRuntimeException(engine, e, ScriptVirtualPath)) { throw; } } }
public void TestListAssemblies() { var meth = DynamicFunction.CreateFunction("SquareX", "public static double SquareX(double x){return x * x;}", null, null, null); var result = DynamicFunction.RunFunctionRedirectOutput(meth, new object[] { (double)3 }); Assert.AreEqual(result.Item1, 9.0); var cslist = BuildHelper.GetAssemblyList(); cslist = cslist.OrderBy(c => c).ToArray(); Assert.IsTrue(cslist.Length > 0); var thispath = Path.Combine("..", "..", "..", ".."); var tpath = Path.Combine(thispath, "csdependencies.txt"); File.WriteAllText(tpath, string.Join("\n", cslist)); }
DynamicFunction CreateCachedMethodFor(DynamicFunction @delegate) { var methodName = (@delegate as Delegate).Method.Name; var newDelegate = new DynamicFunction(() => { if (parameterlessFunctions.ContainsKey(methodName)) return parameterlessFunctions[methodName]; var result = (@delegate as Delegate).Method.Invoke(instance, null); parameterlessFunctions.Add(methodName, result); return parameterlessFunctions[methodName]; }); return newDelegate; }
private void ExecuteFunction(object parameter) { try { if (!string.IsNullOrEmpty(DynamicFunction) && parameter is DataGrid dataGrid) { var replaceColumnIndex = 0; var replaceColumnValue = string.Empty; foreach (var column in ColumnsDictionary) { if (DynamicFunction.Contains(column.Value)) { replaceColumnValue = column.Value; replaceColumnIndex = column.Key; } } var ingnoreFirstRow = false; foreach (var row in CleanDataItems) { if (ingnoreFirstRow) { var newFunction = DynamicFunction.Replace(replaceColumnValue, row.Data[replaceColumnIndex]); var returnValue = _dynamicFunctions.InvokeDynamicFunction(newFunction); if (returnValue is Exception exception) { throw exception; } else { row.Data[replaceColumnIndex] = returnValue.ToString(); } } ingnoreFirstRow = true; } CreateColumnsAndBindings(dataGrid, CleanDataItems.FirstOrDefault().Data.Count); } } catch (Exception ex) { _exceptionLogDataAccess.LogException(ex.ToString()); } }
internal override bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f) { // Does it look like a handler? if (!handlerName.StartsWith(HandlerPrefix)) { return(false); } // Handle the special pseudo-events if (String.Equals(handlerName, "Application_OnStart", StringComparison.OrdinalIgnoreCase) || String.Equals(handlerName, "Application_Start", StringComparison.OrdinalIgnoreCase)) { _onStartMethod = f; return(true); } else if (String.Equals(handlerName, "Application_OnEnd", StringComparison.OrdinalIgnoreCase) || String.Equals(handlerName, "Application_End", StringComparison.OrdinalIgnoreCase)) { _onEndMethod = f; return(true); } else if (String.Equals(handlerName, "Session_OnEnd", StringComparison.OrdinalIgnoreCase) || String.Equals(handlerName, "Session_End", StringComparison.OrdinalIgnoreCase)) { // REVIEW: can we support Session_End? throw new Exception("Session_End is not supported!"); } string eventName = handlerName.Substring(HandlerPrefix.Length); // This will throw if the event doesn't exist EventHookupHelper.GetEventInfo(type, eventName, f, ScriptVirtualPath); if (_eventHandlers == null) { _eventHandlers = new Dictionary <string, DynamicFunction>(); } _eventHandlers[eventName] = f; return(true); }
DynamicFunction CreateCachedMethodFor(DynamicFunction @delegate) { var methodName = (@delegate as Delegate).Method.Name; var newDelegate = new DynamicFunction(() => { if (parameterlessFunctions.ContainsKey(methodName)) { return(parameterlessFunctions[methodName]); } var result = (@delegate as Delegate).Method.Invoke(instance, null); parameterlessFunctions.Add(methodName, result); return(parameterlessFunctions[methodName]); }); return(newDelegate); }
private void RenderMethod(HtmlTextWriter writer, Control container) { ScriptTemplateControl scriptTemplateControl = ScriptTemplateControl.GetScriptTemplateControl(container); // Get the compiled code for the render method logic CompiledCode compiledCode = scriptTemplateControl.GetSnippetRenderCode(container.UniqueID, this); // Execute it in our module EngineHelper.ExecuteCompiledCode(compiledCode, scriptTemplateControl.ScriptModule); // We should always find our render function in the module // REVIEW: we shouldn't have to do this, and should instead work with a lambda like mechanism (bug 218654) object f = scriptTemplateControl.ScriptModule.GetVariable(RenderMethodName); Debug.Assert(f != null); // Call the render method DynamicFunction renderFunction = new DynamicFunction(f); EngineHelper.CallMethod(scriptTemplateControl.ScriptEngine, renderFunction, null /*defaultVirtualPath*/, new SnippetRenderHelper(writer, container.Controls)); }
internal void HookupControlEvent(Control control, string eventName, string handlerName, int line) { EventInfo eventInfo = control.GetType().GetEvent(eventName); if (eventInfo == null) { throw new Exception("Control '" + control.ID + "' doesn't have an event named '" + eventName + "'"); } object o = null; if (_scopeDictionary == null || !_scopeDictionary.TryGetValue(handlerName, out o)) { Misc.ThrowException("The page doesn't have an event handler named '" + handlerName + "'", null, _templateControl.AppRelativeVirtualPath, line); } DynamicFunction handlerFunction = new DynamicFunction(o); Delegate handler = EventHandlerWrapper.GetWrapper(this, handlerFunction, _scriptVirtualPath, eventInfo.EventHandlerType); eventInfo.AddEventHandler(control, handler); }
public void SetDynamicFunction(DynamicFunction f, string virtualPath) { _f = f; _virtualPath = virtualPath; }
public static unsafe int CreateFunction(DataStructure *data) { CreateFunctionInput *inputPtr = (CreateFunctionInput *)data->inputs; Int64 *outputPtr = (Int64 *)data->outputs; string name = BytesToString((sbyte *)inputPtr->namePointer); string code = BytesToString((sbyte *)inputPtr->codePointer); string clrPath = BytesToString((sbyte *)inputPtr->clrPath); sbyte **c_usings = (sbyte **)inputPtr->usingsPointer; var usings = new List <string>(); while (*c_usings != null) { usings.Add(BytesToString(*c_usings)); c_usings++; } sbyte **c_dependencies = (sbyte **)inputPtr->dependenciesPointer; var dependencies = new List <string>(); while (*c_dependencies != null) { dependencies.Add(BytesToString(*c_dependencies)); c_dependencies++; } string text = ""; MethodInfo meth; try { meth = DynamicFunction.CreateFunction(name, code, usings.ToArray(), dependencies.ToArray(), clrPath); } catch (Exception exc) { meth = null; text = exc.ToString(); text = string.Format("Unable to compile function '{0}' due to {1}\n---CODE---\n{2}\n---USINGS---\n{3}\n---DEPENDENCIES---\n{4}\n---", name, exc.ToString(), code, string.Join("\n", usings), string.Join("\n", dependencies)); } if (meth != null) { try { text = DynamicFunction.MethodSignature(meth); } catch (Exception exc) { meth = null; text = string.Format("Unable to get the signature due to: {0}.", exc.ToString()); } } else if (string.IsNullOrEmpty(text)) { text = string.Format("Method '{0}' is null\n---CODE---\n{1}\n---USINGS---\n{2}\n---DEPENDENCIES---\n{3}\n---", name, code, string.Join("\n", usings), string.Join("\n", dependencies)); } *outputPtr = meth == null ? -1 : ObjectStorage.Inst.AddIncref(meth); if (meth == null) { text = text.Replace("\r", "").Replace("\n\n", "\n"); } var raw = StringToNullTerminatedBytesUTF8(text); NativeAllocation allocate = MarshalDelegate <NativeAllocation>(data->allocate_fct); allocate(raw.Length, out data->exc); Marshal.Copy(raw, 0, (IntPtr)data->exc, raw.Length); return(0); }
internal abstract bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f);
public object CallFunction(DynamicFunction f, params object[] args) { return(EngineHelper.CallMethod(_scriptEngine, f, _scriptVirtualPath, args)); }
public object CallDataBindingFunction(DynamicFunction f, params object[] args) { return(CallDataBindingFunction((object)null, f, args)); }
internal override bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f) { // Does it look like a handler? if (!handlerName.StartsWith(HandlerPrefix)) { return(false); } string eventName = handlerName.Substring(HandlerPrefix.Length); EventHookupHelper helper = EventHookupHelper.Create(type, eventName, handlerName, f, ScriptVirtualPath); if (helper == null) { return(false); } if (_eventHandlers == null) { _eventHandlers = new List <EventHookupHelper>(); } _eventHandlers.Add(helper); return(true); }
public static ExpandoObject AddMethod(this ExpandoObject self, string name, DynamicMethod m) { DynamicFunction f = (args) => m(self, args); return(AddField(self, name, f)); }
/// <summary> /// Compiles the functions. /// </summary> /// <remarks><pre> /// 20 Dec 2005 - Jeremy Roberts /// </pre></remarks> protected void compile() { // Code to set up the object. // Create a new AppDomain. // Set up assembly. // //NewAppDomain = System.AppDomain.CreateDomain("NewApplicationDomain"); //NewAppDomain = appDomain; AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "EmittedAssembly"; AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( //AssemblyBuilder assembly = NewAppDomain.DefineDynamicAssembly( assemblyName, //AssemblyBuilderAccess.Save); AssemblyBuilderAccess.Run); //AssemblyBuilderAccess.RunAndSave); // Add Dynamic Module // ModuleBuilder module; module = assembly.DefineDynamicModule("EmittedModule"); TypeBuilder dynamicFunctionClass = module.DefineType( "DynamicFunction", TypeAttributes.Public, typeof(DynamicFunction)); // Define class constructor // Type objType = Type.GetType("System.Object"); ConstructorInfo objConstructor = objType.GetConstructor(new Type[0]); Type[] constructorParams = { }; ConstructorBuilder constructor = dynamicFunctionClass.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, constructorParams); // Emit the class constructor. // ILGenerator constructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, objConstructor); constructorIL.Emit(OpCodes.Ret); // Define "EvaluateD" function. // Type[] args = { typeof(Dictionary<string, double>) }; MethodBuilder evalMethodD = dynamicFunctionClass.DefineMethod( "EvaluateD", MethodAttributes.Public | MethodAttributes.Virtual, typeof(double), args); ILGenerator methodILD; methodILD = evalMethodD.GetILGenerator(); emitFunction(this.PostFix, methodILD); // Define "EvaluateB" function. // MethodBuilder evalMethodB = dynamicFunctionClass.DefineMethod( "EvaluateB", MethodAttributes.Public | MethodAttributes.Virtual, typeof(bool), args); ILGenerator methodILB; methodILB = evalMethodB.GetILGenerator(); emitFunction(this.PostFix, methodILB); // Create an object to use. // Type dt = dynamicFunctionClass.CreateType(); //assembly.Save("assem.dll"); //assembly.Save("x.exe"); //return (function)Activator.CreateInstance(dt, new Object[] { }); this.dynamicFunction = (DynamicFunction)Activator.CreateInstance(dt, new Object[] { }); }
/// <summary> /// Compiles the functions. /// </summary> /// <remarks><pre> /// 20 Dec 2005 - Jeremy Roberts /// </pre></remarks> protected void compile() { // Code to set up the object. // Create a new AppDomain. // Set up assembly. // //NewAppDomain = System.AppDomain.CreateDomain("NewApplicationDomain"); //NewAppDomain = appDomain; AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "EmittedAssembly"; AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( //AssemblyBuilder assembly = NewAppDomain.DefineDynamicAssembly( assemblyName, //AssemblyBuilderAccess.Save); AssemblyBuilderAccess.Run); //AssemblyBuilderAccess.RunAndSave); // Add Dynamic Module // ModuleBuilder module; module = assembly.DefineDynamicModule("EmittedModule"); TypeBuilder dynamicFunctionClass = module.DefineType( "DynamicFunction", TypeAttributes.Public, typeof(DynamicFunction)); // Define class constructor // Type objType = Type.GetType("System.Object"); ConstructorInfo objConstructor = objType.GetConstructor(new Type[0]); Type[] constructorParams = { }; ConstructorBuilder constructor = dynamicFunctionClass.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, constructorParams); // Emit the class constructor. // ILGenerator constructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, objConstructor); constructorIL.Emit(OpCodes.Ret); // Define "EvaluateD" function. // Type[] args = { typeof(Dictionary <string, double>) }; MethodBuilder evalMethodD = dynamicFunctionClass.DefineMethod( "EvaluateD", MethodAttributes.Public | MethodAttributes.Virtual, typeof(double), args); ILGenerator methodILD; methodILD = evalMethodD.GetILGenerator(); emitFunction(this.PostFix, methodILD); // Define "EvaluateB" function. // MethodBuilder evalMethodB = dynamicFunctionClass.DefineMethod( "EvaluateB", MethodAttributes.Public | MethodAttributes.Virtual, typeof(bool), args); ILGenerator methodILB; methodILB = evalMethodB.GetILGenerator(); emitFunction(this.PostFix, methodILB); // Create an object to use. // Type dt = dynamicFunctionClass.CreateType(); //assembly.Save("assem.dll"); //assembly.Save("x.exe"); //return (function)Activator.CreateInstance(dt, new Object[] { }); this.dynamicFunction = (DynamicFunction)Activator.CreateInstance(dt, new Object[] { }); }