public void RemoveEventHandler(object target, Delegate handler) { var removeMethod = GetRemoveMethod(); if (removeMethod == null) throw new InvalidOperationException("no public remove method"); removeMethod.Invoke(target, new object[] { handler }); }
public void AddEventHandler(object target, Delegate handler) { var addMethod = GetAddMethod(); if (addMethod == null) throw new InvalidOperationException("no public add method"); addMethod.Invoke(target, new object[] { handler }); }
///////////////////////////////////////////////////// // track methods ///////////////////////////////////////////////////// public void addTrack(String name, Delegate onCompleteHandler=null) { if(_tracks.ContainsKey(name) == false){ _tracks[name] = new SoundTrack( new Sound( name ), gameObject, onCompleteHandler ); _tracks[name].volume = _trackVolume; } }
public InterestCalculator(decimal money, decimal interest, int years, Delegate del) { this.Money = money; this.Interest = interest; this.Years = years; this.PayOutValue = del(money, interest, years); }
public sealed override void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = this.AddMethod; if (!addMethod.IsPublic) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); addMethod.Invoke(target, new Object[] { handler }); }
/// <summary> /// Concatenates an invocation list of 2 delegates. /// </summary> public static Delegate Combine(Delegate a, Delegate b) { if (a == null) return b; if (b == null) return a; a.Add(b); return a; }
private float _volumeRatio = 1; // sound volume ratio #endregion Fields #region Constructors /** * INIT soundTrack, hook up controls * @param soundObject: Sound * @param gameObject: GameObject * @param onCompleteHandler: Delegate **/ public SoundTrack(Sound soundObject, GameObject gameObject, Delegate onCompleteHandler=null) { _soundObj = soundObject; _channel = gameObject.AddComponent("AudioSource") as AudioSource; _channel.clip = _soundObj.clip; _complete = onCompleteHandler; }
// Adds an EventKey -> Delegate mapping if it doesn't exist or // combines a delegate to an existing EventKey public void Add(EventKey eventKey, Delegate handler) { Monitor.Enter(m_events); Delegate d; m_events.TryGetValue(eventKey, out d); m_events[eventKey] = Delegate.Combine(d, handler); Monitor.Exit(m_events); }
public void Unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.startEventField != null) { this.unbindEvent(this.startEventField, this.startEventHandler); this.startEventField = null; this.startEventHandler = null; } if (this.stopEventField != null) { this.unbindEvent(this.stopEventField, this.stopEventHandler); this.stopEventField = null; this.stopEventHandler = null; } if (this.resetEventField != null) { this.unbindEvent(this.resetEventField, this.resetEventHandler); this.resetEventField = null; this.resetEventHandler = null; } }
protected override Delegate RemoveImpl(Delegate d) { MulticastDelegate ret = null, cur = null; for (MulticastDelegate del = this; del != null; del = (MulticastDelegate)del.mNext) { // Miss out the one we're removing if (!del.Equals(d)) { if (ret == null) { ret = (MulticastDelegate)object.MemberwiseClone(del); cur = ret; } else { cur.mNext = (MulticastDelegate)object.MemberwiseClone(del); cur = (MulticastDelegate)cur.mNext; } } } if (cur != null) { cur.mNext = null; } return ret; }
public DelegateData(Delegate del, Type delType, Type module, BuildingEvents[] ID) { delegateInstance = del; moduleType = module; eventID = ID; delegateType = delType; }
public ContinuationTaskFromTask(Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, antecedent.Scheduler) { Contract.Requires(action is Action<Task> || action is Action<Task, object>, "Invalid delegate type in ContinuationTaskFromTask"); _antecedent = antecedent; CapturedContext = ExecutionContext.Capture(); }
public void registerDelegate(Delegate newOne) /* pre: Have a list of delegates which could be empty. For the new delegate, have delegate identifier, name, topic * and whether presenting (true) or not (false). * post: Register a delegate by adding him/her to the top of the delegates stack. A delegate may only be a presenter * if there is a presentation slot available (use availSlots), otherwise register the delegate and display an * appropriate message. NO DUPLICATE DELEGATES ARE REGISTERED (on delegate identifier) - display an appropriate * message in such a case. */ { Stack temp = new Stack(); Delegate cur; bool foundPos = false; while ((Delegates.Count > 0) && (!foundPos)) { cur = (Delegate)Delegates.Pop(); temp.Push(cur); if (cur.Equals(newOne)) foundPos = true; } while (temp.Count > 0) Delegates.Push(temp.Pop()); if (foundPos) Console.WriteLine("Delegate " + newOne.DelID + " already registered."); else { if (newOne.Presenter) if (availSlots() < 1) { Console.WriteLine("Delegate {0} registered but cannot present - not enough slots", newOne.DelID); newOne.Presenter = false; } Delegates.Push(newOne); } }
/// <summary> /// Executes the specified delegate with the specified arguments /// asynchronously on a thread pool thread /// </summary> /// <param name="d"></param> /// <param name="args"></param> public static void FireAndForget(Delegate d, params object[] args) { // Invoke the wrapper asynchronously, which will then // execute the wrapped delegate synchronously (in the // thread pool thread) if (d != null) wrapperInstance.BeginInvoke(d, args, callback, null); }
/// <summary> /// Gets the current value of the parameter given (optional) compiled query arguments. /// </summary> internal object EvaluateParameter(object[] arguments) { if (_cachedDelegate == null) { if (_funcletizedExpression.NodeType == ExpressionType.Constant) { return ((ConstantExpression)_funcletizedExpression).Value; } ConstantExpression ce; if (TryEvaluatePath(_funcletizedExpression, out ce)) { return ce.Value; } } try { if (_cachedDelegate == null) { // Get the Func<> type for the property evaluator var delegateType = TypeSystem.GetDelegateType(_compiledQueryParameters.Select(p => p.Type), _type); // Now compile delegate for the funcletized expression _cachedDelegate = Lambda(delegateType, _funcletizedExpression, _compiledQueryParameters).Compile(); } return _cachedDelegate.DynamicInvoke(arguments); } catch (TargetInvocationException e) { throw e.InnerException; } }
public static MethodInfo GetDelegateMethodInfo(Delegate del) { if (del == null) throw new ArgumentException(); Delegate[] invokeList = del.GetInvocationList(); del = invokeList[invokeList.Length - 1]; RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate; bool isOpenResolver; IntPtr originalLdFtnResult = RuntimeAugments.GetDelegateLdFtnResult(del, out typeOfFirstParameterIfInstanceDelegate, out isOpenResolver); if (originalLdFtnResult == (IntPtr)0) return null; MethodHandle methodHandle = default(MethodHandle); RuntimeTypeHandle[] genericMethodTypeArgumentHandles = null; bool callTryGetMethod = true; unsafe { if (isOpenResolver) { OpenMethodResolver* resolver = (OpenMethodResolver*)originalLdFtnResult; if (resolver->ResolverType == OpenMethodResolver.OpenNonVirtualResolve) { originalLdFtnResult = resolver->CodePointer; // And go on to do normal ldftn processing. } else if (resolver->ResolverType == OpenMethodResolver.DispatchResolve) { callTryGetMethod = false; methodHandle = resolver->Handle.AsMethodHandle(); genericMethodTypeArgumentHandles = null; } else { System.Diagnostics.Debug.Assert(resolver->ResolverType == OpenMethodResolver.GVMResolve); callTryGetMethod = false; methodHandle = resolver->Handle.AsMethodHandle(); RuntimeTypeHandle declaringTypeHandleIgnored; MethodNameAndSignature nameAndSignatureIgnored; if (!TypeLoaderEnvironment.Instance.TryGetRuntimeMethodHandleComponents(resolver->GVMMethodHandle, out declaringTypeHandleIgnored, out nameAndSignatureIgnored, out genericMethodTypeArgumentHandles)) return null; } } } if (callTryGetMethod) { if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForOriginalLdFtnResult(originalLdFtnResult, ref typeOfFirstParameterIfInstanceDelegate, out methodHandle, out genericMethodTypeArgumentHandles)) return null; } MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod(typeOfFirstParameterIfInstanceDelegate, methodHandle, genericMethodTypeArgumentHandles); MethodInfo methodInfo = methodBase as MethodInfo; if (methodInfo != null) return methodInfo; return null; // GetMethod() returned a ConstructorInfo. }
protected virtual Delegate RemoveImpl(Delegate d) { if (d.Equals(this)) { return null; } return this; }
public static Delegate Remove(Delegate source, Delegate value) { if (source == null) { return null; } return source.RemoveImpl(value); }
static void Main () { Delegate [] d = new Delegate [] { new Function<int, int, bool> (f1) }; Assert.AreEqual (1, d.Length, "#1"); MethodInfo mi = d [0].Method; Assert.AreEqual (typeof (Program), mi.DeclaringType, "#2"); Assert.AreEqual ("Boolean f1(Int32, Int32)", mi.ToString (), "#2"); }
public virtual void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = AddMethod; if (!addMethod.IsPublic) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); addMethod.Invoke(target, new object[] { handler }); }
public virtual void RemoveEventHandler(Object target, Delegate handler) { MethodInfo removeMethod = RemoveMethod; if (!removeMethod.IsPublic) throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); removeMethod.Invoke(target, new object[] { handler }); }
public static void DisplayDelegateInfo(Delegate del) { foreach (var item in del.GetInvocationList()) { Console.WriteLine("Method Name {0}", del.Method); Console.WriteLine("Type Name {0}", del.Target); } }
public void Add(EventPrivateKey key, Delegate handler) { if (_directEventHandlers == null) { _directEventHandlers = new EventHandlerList(); } _directEventHandlers.AddHandler(key, handler); }
public void AddRoutedEventHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo) { if (_routedEventHandlers == null) { _routedEventHandlers = new RoutedEventHandlerInfoList(); } _routedEventHandlers.AddHandler(routedEvent, handler, handledEventsToo); }
public void Remove(EventPrivateKey key, Delegate handler) { if (_directEventHandlers == null) { return; } _directEventHandlers.RemoveHandler(key, handler); }
public static void PrintInvocationList(Delegate someDelegate) { Console.Write("("); Delegate[] list = someDelegate.GetInvocationList(); foreach (Delegate del in list) { Console.Write(" {0}", del.Method.Name); } Console.WriteLine(" )"); }
static void Main() { int t = 2000; Delegate d = new Delegate(TestMethod); while (true) { d(); Thread.Sleep(t); } }
internal void UnregisterEvent(string eventName, Delegate eventMethod) { if(_eventTable.ContainsKey(eventName)) { if(_eventTable[eventName].GetInvocationList().Length <= 0) _eventTable.Remove (eventName); else _eventTable[eventName] -= eventMethod; } }
static MacSupport () { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) { if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) { Type driver_type = asm.GetType ("System.Windows.Forms.XplatUICarbon"); if (driver_type != null) { hwnd_delegate = (Delegate) driver_type.GetField ("HwndDelegate", BindingFlags.NonPublic | BindingFlags.Static).GetValue (null); } } } }
static public void OnListenerAdding(string eventType, Delegate listenerBeingAdded) { if (!eventTable.ContainsKey(eventType)) { eventTable.Add(eventType, null); } Delegate d = eventTable[eventType]; if (d != null && d.GetType() != listenerBeingAdded.GetType()) { throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name)); } }
#pragma warning disable 0169 static Delegate GetSetSmsFormat_Ljava_lang_String_Ljava_lang_String_Handler () { if (cb_setSmsFormat_Ljava_lang_String_Ljava_lang_String_ == null) cb_setSmsFormat_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_SetSmsFormat_Ljava_lang_String_Ljava_lang_String_); return cb_setSmsFormat_Ljava_lang_String_Ljava_lang_String_; }
#pragma warning disable 0169 static Delegate GetGetTabSelectedIconHandler () { if (cb_getTabSelectedIcon == null) cb_getTabSelectedIcon = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetTabSelectedIcon); return cb_getTabSelectedIcon; }
/// <summary> /// Declare user function into the PHP runtime context. /// </summary> /// <param name="name">Global PHP function name.</param> /// <param name="delegate">Delegate to represent the PHP function.</param> public void DeclareFunction(string name, Delegate @delegate) => _functions.DeclarePhpRoutine(RoutineInfo.CreateUserRoutine(name, @delegate));
private void Awake() { List <Assembly> assemblies = new List <Assembly>(); foreach (string assemblyName in BHPath.RootAssemblies) { var asName = new AssemblyName(); asName.Name = assemblyName; Assembly asm = Assembly.Load(asName); if (asm == null) { Debug.LogWarning("Unable to load " + assemblyName); continue; } assemblies.Add(asm); } if (m_menuPanel == null) { m_menuPanel = gameObject; } if (m_topMenu == null) { m_topMenu = gameObject; } if (m_menuButtonPrefab == null) { Debug.LogError("Set Menu Button Prefab"); return; } if (m_menuPrefab == null) { Debug.LogError("Set Menu Prefab"); return; } bool wasButtonPrefabActive = m_menuButtonPrefab.gameObject.activeSelf; bool wasMenuPrefabActive = m_menuPrefab.gameObject.activeSelf; Dictionary <string, Menu> menuDictionary = new Dictionary <string, Menu>(); Dictionary <string, List <MenuItemInfo> > menuItemsDictionary = new Dictionary <string, List <MenuItemInfo> >(); Menu[] menus = m_menuPanel.GetComponentsInChildren <Menu>(true); for (int i = 0; i < menus.Length; ++i) { if (!menuDictionary.ContainsKey(menus[i].name)) { menuDictionary.Add(menus[i].name, menus[i]); if (menus[i].Items != null) { menuItemsDictionary.Add(menus[i].name, menus[i].Items.ToList()); } else { menuItemsDictionary.Add(menus[i].name, new List <MenuItemInfo>()); } } } Type[] menuDefinitions = assemblies.SelectMany(asm => asm.GetTypesWithAttribute(typeof(MenuDefinitionAttribute))).ToArray(); foreach (Type menuDef in menuDefinitions) { MethodInfo[] methods = menuDef.GetMethods(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < methods.Length; ++i) { MethodInfo mi = methods[i]; MenuCommandAttribute cmd = (MenuCommandAttribute)mi.GetCustomAttributes(typeof(MenuCommandAttribute), true).FirstOrDefault(); if (string.IsNullOrEmpty(cmd.Path)) { continue; } string[] pathParts = cmd.Path.Split('/'); if (pathParts.Length < 1) { continue; } string menuName = pathParts[0]; Menu menu; if (!menuDictionary.ContainsKey(menuName)) { m_menuButtonPrefab.gameObject.SetActive(false); m_menuPrefab.gameObject.SetActive(false); menu = Instantiate(m_menuPrefab, m_menuPanel.transform, false); menu.Items = null; MainMenuButton btn = Instantiate(m_menuButtonPrefab, m_topMenu.transform, false); btn.name = menuName; btn.Menu = menu; Text txt = btn.GetComponentInChildren <Text>(true); if (txt != null) { txt.text = menuName; } btn.gameObject.SetActive(true); menuDictionary.Add(menuName, menu); menuItemsDictionary.Add(menuName, new List <MenuItemInfo>()); } else { menu = menuDictionary[menuName]; } if (pathParts.Length == 1) { if (cmd.Hide) { menuItemsDictionary[menuName].Clear(); } } if (pathParts.Length < 2) { continue; } string path = string.Join("/", pathParts.Skip(1)); List <MenuItemInfo> menuItems = menuItemsDictionary[menuName]; MenuItemInfo menuItem = menuItems.Where(item => item.Path == path).FirstOrDefault(); if (menuItem == null) { menuItem = new MenuItemInfo(); menuItems.Add(menuItem); } menuItem.Path = string.Join("/", pathParts.Skip(1)); menuItem.Icon = !string.IsNullOrEmpty(cmd.IconPath) ? Resources.Load <Sprite>(cmd.IconPath) : null; menuItem.Text = pathParts.Last(); if (cmd.Validate) { Func <bool> validate = (Func <bool>)Delegate.CreateDelegate(typeof(Func <bool>), mi, false); if (validate == null) { Debug.LogWarning("method signature is invalid. bool Func() is expected. " + string.Join("/", pathParts)); } else { menuItem.Validate = new MenuItemValidationEvent(); menuItem.Validate.AddListener(new UnityAction <MenuItemValidationArgs>(args => args.IsValid = validate())); } } else { Action action = (Action)Delegate.CreateDelegate(typeof(Action), mi, false); if (action == null) { Debug.LogWarning("method signature is invalid. void Action() is expected. " + string.Join("/", pathParts)); } else { menuItem.Action = new MenuItemEvent(); menuItem.Action.AddListener(new UnityAction <string>(args => action())); } } if (cmd.Hide) { menuItems.Remove(menuItem); } } m_menuPrefab.gameObject.SetActive(wasMenuPrefabActive); m_menuButtonPrefab.gameObject.SetActive(wasButtonPrefabActive); } foreach (KeyValuePair <string, List <MenuItemInfo> > kvp in menuItemsDictionary) { menuDictionary[kvp.Key].SetMenuItems(kvp.Value.ToArray(), false); } }
public sealed override MethodInfo GetDelegateMethod(Delegate del) { return(DelegateMethodInfoRetriever.GetDelegateMethodInfo(del)); }
public Hook(MethodBase method, Delegate to) : this(method, to.Method, to.Target) { }
// // Helper to create a delegate on a runtime-supplied type. // public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) { return(Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic: isStatic, isOpen: isOpen)); }
/// <summary> /// create a delegate from a method /// </summary> /// <typeparam name="TDelegate"></typeparam> /// <param name="methodInfo"></param> /// <returns></returns> public static TDelegate CreateDelegate <TDelegate>(MethodInfo methodInfo) where TDelegate : Delegate { return((TDelegate)Delegate.CreateDelegate(typeof(TDelegate), methodInfo)); }
public Hook(MethodBase method, Delegate to, HookConfig config) : this(method, to.Method, to.Target, ref config) { }
/// <summary> /// Important method that wires and connects all the classes and interfaces together to run the application. /// If object A (this) has a private field of an interface, and object B implements the interface, then wire them together. Returns this for fluent style programming. /// ------------------------------------------------------------------------------------------------------------------ /// WireTo methods five important keys: /// 1. wires match interfaces, A (calls interface) and B (implements) /// 2. interfaces must be all private for matching to happen /// 3. can wire multiple matching interfaces /// 4. wires in order form top to bottom of not yet wired /// 5. can ovveride order by specifying port names as second parameter /// 6. looks for list as well (be careful of blocking other interfaces from wiring) /// ------------------------------------------------------------------------------------------------------------------ /// </summary> /// <param name="A"> /// The object on which the method is called is the object being wired from /// </param> /// <param name="B">The object being wired to (must implement the interface)</param> /// <returns></returns> /// <remarks> /// If A has two private fields of the same interface, the first compatible B object wired goes to the first one and the second compatible B object wired goes to the second. /// If A has multiple private interfaces of different types, only the first matching interface that B implements will be wired. /// In other words, by default, only one interface is wired between A and B /// To override this behaviour you can get give multiple interfaces in A a prefix "Pn_" where n is 0..9: /// Then a single wiring operation will wire all fieldnames with a consistent port prefix to the same B. /// These remarks apply only to single fields, not Lists. /// e.g. /// private IOneable client1Onabale; /// private ITwoable client1Twoable; /// private IThreeable client2; /// Clearly we want to wire two different clients. But if the first client wired implements all three interfaces, it will be wired to all three fields. /// So name the field like this: /// private IOneable P1_clientOnabale; /// private ITwoable P1_clientTwoable; /// private IThreeable P2_client; /// </remarks> public static T WireTo <T>(this T A, object B, string APortName = null, bool reverse = false) { string multiportExceptionMessage = $"The following wiring failed because the two instances are already wired together by another port."; multiportExceptionMessage += "\nPlease use a new WireTo with this additional port name specified:"; if (A == null) { throw new ArgumentException("A cannot be null"); } if (B == null) { throw new ArgumentException("B cannot be null"); } // achieve the following via reflection // A.field = (<type of interface>)B; // A.list.Add( (<type of interface>)B ); // Get the two instance name first for the Debug Output WriteLines var AinstanceName = A.GetType().GetProperties().FirstOrDefault(f => f.Name == "InstanceName")?.GetValue(A); if (AinstanceName == null) { AinstanceName = A.GetType().GetFields().FirstOrDefault(f => f.Name == "InstanceName")?.GetValue(A); } var BinstanceName = B.GetType().GetProperties().FirstOrDefault(f => f.Name == "InstanceName")?.GetValue(B); if (BinstanceName == null) { BinstanceName = B.GetType().GetFields().FirstOrDefault(f => f.Name == "InstanceName")?.GetValue(B); } var BType = B.GetType(); var AfieldInfos = A.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .Where(f => (APortName == null || f.Name == APortName) && (!reverse ^ EndsIn_B(f.Name))).ToList(); // find the fields that the name meets all criteria // TODO: when not reverse ports ending in _B should be excluded //if (A.GetType().Name=="DragDrop" && AinstanceName=="Initial Tag") //{ // for breakpoint //} var wiredSomething = false; firstPortName = null; foreach (var BimplementedInterface in BType.GetInterfaces()) // consider every interface implemented by B { var AfieldInfo = AfieldInfos.FirstOrDefault(f => f.FieldType == BimplementedInterface && f.GetValue(A) == null); // find the first field in A that matches the interface type of B // TODO: the list case below should have the SamePort constraint as well // look for normal private fields first if (AfieldInfo != null) // there is a match { if (SamePort(AfieldInfo.Name)) { if (wiredSomething) { string exceptionMessage = multiportExceptionMessage + "\n" + OutputWiring(A, B, AfieldInfo, save: false); // throw new Exception(exceptionMessage); } AfieldInfo.SetValue(A, B); // do the wiring wiredSomething = true; OutputWiring(A, B, AfieldInfo); } continue; // could be more than one interface to wire } // do the same as above for private fields that are a list of the interface of the matching type foreach (var AlistFieldInfo in AfieldInfos) { if (!AlistFieldInfo.FieldType.IsGenericType) //not matching interface { continue; } var AListFieldValue = AlistFieldInfo.GetValue(A); var AListGenericArguments = AlistFieldInfo.FieldType.GetGenericArguments(); if (AListGenericArguments.Length != 1) { continue; // A list should only have one type anyway } if (AListGenericArguments[0].IsAssignableFrom(BimplementedInterface)) // JRS: There was some case where == didn't work, maybe in the gamescoring application { if (AListGenericArguments[0] != BimplementedInterface) { var g = AListGenericArguments[0]; if (g != typeof(object)) { throw new Exception("Different types"); } continue; } if (AListFieldValue == null) { var listType = typeof(List <>); Type[] listParam = { BimplementedInterface }; AListFieldValue = Activator.CreateInstance(listType.MakeGenericType(listParam)); if (wiredSomething) { string exceptionMessage = multiportExceptionMessage + "\n" + OutputWiring(A, B, AListFieldValue, save: false); throw new Exception(exceptionMessage); } AlistFieldInfo.SetValue(A, AListFieldValue); } AListFieldValue.GetType().GetMethod("Add").Invoke(AListFieldValue, new[] { B }); wiredSomething = true; OutputWiring(A, B, AlistFieldInfo); break; } } } if (!reverse && !wiredSomething) { if (APortName != null) { // a specific port was specified so see if the port was already wired var value = AfieldInfos.FirstOrDefault()?.GetValue(A); if (value != null && !(value is IList)) { throw new Exception($"Port already wired {A.GetType().Name}[{AinstanceName}].{APortName} to {BType.Name}[{BinstanceName}]"); } } //throw new Exception($"Failed to wire {A.GetType().Name}[{AinstanceName}].{APortName} to {BType.Name}[{BinstanceName}]"); } // PostWiringInitialize for A var postWiringMethod = A.GetType().GetMethod("PostWiringInitialize", BindingFlags.NonPublic | BindingFlags.Instance); if (postWiringMethod != null) { InitializeDelegate handler = (InitializeDelegate)Delegate.CreateDelegate(typeof(InitializeDelegate), A, postWiringMethod); PostWiring -= handler; // instances can be wired to/from more than once, so only register their PostWiringInitialize once PostWiring += handler; } // PostWiringInitialize for B postWiringMethod = B.GetType().GetMethod("PostWiringInitialize", BindingFlags.NonPublic | BindingFlags.Instance); if (postWiringMethod != null) { InitializeDelegate handler = (InitializeDelegate)Delegate.CreateDelegate(typeof(InitializeDelegate), B, postWiringMethod); PostWiring -= handler; // instances can be wired to/from more than once, so only register their PostWiringInitialize once PostWiring += handler; } var onWiringMethod = A.GetType().GetMethod("OnWiringInitialize", BindingFlags.NonPublic | BindingFlags.Instance); if (onWiringMethod != null) { InitializeDelegate handler = (InitializeDelegate)Delegate.CreateDelegate(typeof(InitializeDelegate), A, onWiringMethod); OnWiring += handler; OnWiringInitialize(); OnWiring -= handler; // OnWiringInitialize() is always called after wiring, so we remove the handler to avoid it being invoked again on the next wiring } return(A); }
public Engine SetValue(string name, Delegate value) { Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true); return(this); }
/// <summary>Default constructor, creates the UIElements including a PropertyInspector</summary> public WpfPropertyGrid() { this.ColumnDefinitions.Add(new ColumnDefinition()); this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0) }); this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0) }); this.Designer = new WorkflowDesigner(); TextBlock title = new TextBlock() { Visibility = Windows.Visibility.Visible, TextWrapping = TextWrapping.NoWrap, TextTrimming = TextTrimming.CharacterEllipsis, FontWeight = FontWeights.Bold }; TextBlock descrip = new TextBlock() { Visibility = Windows.Visibility.Visible, TextWrapping = TextWrapping.Wrap, TextTrimming = TextTrimming.CharacterEllipsis }; DockPanel dock = new DockPanel() { Visibility = Windows.Visibility.Visible, LastChildFill = true, Margin = new Thickness(3, 0, 3, 0) }; title.SetValue(DockPanel.DockProperty, Dock.Top); dock.Children.Add(title); dock.Children.Add(descrip); this.HelpText = new Border() { Visibility = Windows.Visibility.Visible, BorderBrush = SystemColors.ActiveBorderBrush, Background = SystemColors.ControlBrush, BorderThickness = new Thickness(1), Child = dock }; this.Splitter = new GridSplitter() { Visibility = Windows.Visibility.Visible, ResizeDirection = GridResizeDirection.Rows, Height = 5, HorizontalAlignment = Windows.HorizontalAlignment.Stretch }; var inspector = Designer.PropertyInspectorView; inspector.Visibility = Visibility.Visible; inspector.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Stretch); this.Splitter.SetValue(Grid.RowProperty, 1); this.Splitter.SetValue(Grid.ColumnProperty, 0); this.HelpText.SetValue(Grid.RowProperty, 2); this.HelpText.SetValue(Grid.ColumnProperty, 0); Binding binding = new Binding("Parent.Background"); title.SetBinding(BackgroundProperty, binding); descrip.SetBinding(BackgroundProperty, binding); this.Children.Add(inspector); this.Children.Add(this.Splitter); this.Children.Add(this.HelpText); Type inspectorType = inspector.GetType(); var props = inspectorType.GetProperties(Reflection.BindingFlags.Public | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly); var methods = inspectorType.GetMethods(Reflection.BindingFlags.Public | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly); this.RefreshMethod = inspectorType.GetMethod("RefreshPropertyList", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly); this.IsInAlphaViewMethod = inspectorType.GetMethod("set_IsInAlphaView", Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly); this.OnSelectionChangedMethod = inspectorType.GetMethod("OnSelectionChanged", Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly); this.SelectionTypeLabel = inspectorType.GetMethod("get_SelectionTypeLabel", Reflection.BindingFlags.Public | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly).Invoke(inspector, new object[0]) as TextBlock; this.PropertyToolBar = inspectorType.GetMethod("get_PropertyToolBar", Reflection.BindingFlags.Public | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance | Reflection.BindingFlags.DeclaredOnly).Invoke(inspector, new object[0]) as Control; inspectorType.GetEvent("GotFocus").AddEventHandler(this, Delegate.CreateDelegate(typeof(RoutedEventHandler), this, "GotFocusHandler", false)); this.SelectionTypeLabel.Text = string.Empty; }
// Used to mutate the first parameter in a closed static delegate. Note that this does no synchronization of any kind; // use only on delegate instances you're sure nobody else is using. public static void SetClosedStaticDelegateFirstParameter(Delegate del, object firstParameter) { del.SetClosedStaticFirstParameter(firstParameter); }
public Hook(Delegate from, IntPtr to, ref HookConfig config) : this(from.Method, to, ref config) { }
// // Helper to extract the artifact that uniquely identifies a method in the runtime mapping tables. // public static IntPtr GetDelegateLdFtnResult(Delegate d, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver) { return(d.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out isOpenResolver)); }
public Hook(Delegate from, IntPtr to) : this(from.Method, to) { }
public static Delegate CreateObjectArrayDelegate(Type delegateType, Func <object[], object> invoker) { return(Delegate.CreateObjectArrayDelegate(delegateType, invoker)); }
public Hook(Delegate from, Delegate to, HookConfig config) : this(from.Method, to, ref config) { }
/// <summary> /// Unsubscribes from all auto subscribed events. /// </summary> public virtual void Dispose() { var type = this.GetType(); var methods = this.GetType().GetMethods(); foreach (var method in methods) { var attrs = method.GetCustomAttributes(typeof(OnAttribute), false); if (attrs.Length == 0) { continue; } var attr = attrs[0] as OnAttribute; var eventHandlerInfo = ChannelServer.Instance.Events.GetType().GetEvent(attr.Event); if (eventHandlerInfo == null) { // Erroring on load should be enough. //Log.Error("Dispose: Unknown event '{0}' on '{1}.{2}'.", attr.Event, type.Name, method.Name); continue; } try { eventHandlerInfo.RemoveEventHandler(ChannelServer.Instance.Events, Delegate.CreateDelegate(eventHandlerInfo.EventHandlerType, this, method)); } catch (Exception ex) { Log.Exception(ex, "Dispose: Failed to unsubscribe '{1}.{2}' from '{0}'.", attr.Event, type.Name, method.Name); } } this.CleanUp(); }
public Hook(Delegate from, Delegate to) : this(from.Method, to) { }
internal Delegate _CreateDelegate(Type delegateType, string handler) { return Delegate.CreateDelegate(delegateType, (object) this, handler); }
public Hook(Expression from, Delegate to, HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { }
protected static Delegate GetMethod <T>(string methodName) { MethodInfo methodInfo = inputType.GetMethod(methodName); return(Delegate.CreateDelegate(typeof(T), methodInfo)); }
public Hook(Expression from, Delegate to) : this(((MethodCallExpression)from).Method, to) { }
public override void RemoveEventHandler(object component, Delegate value) { (component as FastColoredTextBox).BindingTextChanged -= value as EventHandler; }
public Hook(Expression <Action> from, Delegate to, HookConfig config) : this(from.Body, to, ref config) { }
#pragma warning disable 0169 static Delegate GetGetTabTitleHandler () { if (cb_getTabTitle == null) cb_getTabTitle = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetTabTitle); return cb_getTabTitle; }
public Hook(Expression <Action> from, Delegate to) : this(from.Body, to) { }
/// <summary> /// Initializes a new <see cref="ReflectedMemberProperty{TContainer,TValue}"/> instance. This is an internal constructor. /// </summary> /// <param name="info">The reflected info object backing this property.</param> internal ReflectedMemberProperty(IMemberInfo info) { m_Info = info; m_IsStructContainerType = RuntimeTypeInfoCache <TContainer> .IsValueType; AddAttributes(info.GetCustomAttributes()); var isReadOnly = m_Info.IsReadOnly || HasAttribute <ReadOnlyAttribute>(); IsReadOnly = isReadOnly; if (m_Info is FieldMember fieldMember) { // TODO: optimize for NET_STANDARD, where DynamicMethod is not available by default #if NET_4_6 && !ENABLE_IL2CPP var fieldInfo = fieldMember.m_FieldInfo; // getter var dynamicMethod = new DynamicMethod(string.Empty, fieldInfo.FieldType, new Type[] { m_IsStructContainerType?fieldInfo.ReflectedType.MakeByRefType() : fieldInfo.ReflectedType }, true); var ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, fieldInfo); ilGenerator.Emit(OpCodes.Ret); if (m_IsStructContainerType) { m_GetStructValueAction = (GetStructValueAction)dynamicMethod.CreateDelegate(typeof(GetStructValueAction)); } else { m_GetClassValueAction = (GetClassValueAction)dynamicMethod.CreateDelegate(typeof(GetClassValueAction)); } // settter if (!isReadOnly) { dynamicMethod = new DynamicMethod(string.Empty, typeof(void), new Type[] { m_IsStructContainerType?fieldInfo.ReflectedType.MakeByRefType() : fieldInfo.ReflectedType, fieldInfo.FieldType }, true); ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_1); ilGenerator.Emit(OpCodes.Stfld, fieldInfo); ilGenerator.Emit(OpCodes.Ret); if (m_IsStructContainerType) { m_SetStructValueAction = (SetStructValueAction)dynamicMethod.CreateDelegate(typeof(SetStructValueAction)); } else { m_SetClassValueAction = (SetClassValueAction)dynamicMethod.CreateDelegate(typeof(SetClassValueAction)); } } #endif } else if (m_Info is PropertyMember propertyMember) { if (m_IsStructContainerType) { var getMethod = propertyMember.m_PropertyInfo.GetGetMethod(true); m_GetStructValueAction = (GetStructValueAction)Delegate.CreateDelegate(typeof(GetStructValueAction), getMethod); if (!isReadOnly) { var setMethod = propertyMember.m_PropertyInfo.GetSetMethod(true); m_SetStructValueAction = (SetStructValueAction)Delegate.CreateDelegate(typeof(SetStructValueAction), setMethod); } } else { var getMethod = propertyMember.m_PropertyInfo.GetGetMethod(true); m_GetClassValueAction = (GetClassValueAction)Delegate.CreateDelegate(typeof(GetClassValueAction), getMethod); if (!isReadOnly) { var setMethod = propertyMember.m_PropertyInfo.GetSetMethod(true); m_SetClassValueAction = (SetClassValueAction)Delegate.CreateDelegate(typeof(SetClassValueAction), setMethod); } } } }
public List <string> CompilePeriod() { var CSHarpProvider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters compilerParams = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true, }; compilerParams.ReferencedAssemblies.AddRange(new string[] { "System.dll", }); compilerParams.IncludeDebugInformation = false; var compilerResultPeriod = CSHarpProvider.CompileAssemblyFromSource(compilerParams, FormulaDataSource.CompRangeEnvironment.Replace("{formula}", PeriodFormula)); var compilerResultLow = CSHarpProvider.CompileAssemblyFromSource(compilerParams, FormulaDataSource.CompRangeEnvironment.Replace("{formula}", LowLimFormula)); var compilerResultHigh = CSHarpProvider.CompileAssemblyFromSource(compilerParams, FormulaDataSource.CompRangeEnvironment.Replace("{formula}", HighLimFormula)); if (compilerResultLow.Errors.Count == 0 && compilerResultHigh.Errors.Count == 0 && compilerResultPeriod.Errors.Count == 0) { try { var _baseTypeLow = compilerResultLow.CompiledAssembly.GetType("Func.Function"); var _baseTypeHigh = compilerResultHigh.CompiledAssembly.GetType("Func.Function"); var _baseTypePeriod = compilerResultPeriod.CompiledAssembly.GetType("Func.Function"); Period = ((Func <float>)Delegate.CreateDelegate(typeof(Func <float>), _baseTypePeriod.GetMethod("MainFunction"))).Invoke(); HighLim = ((Func <float>)Delegate.CreateDelegate(typeof(Func <float>), _baseTypeHigh.GetMethod("MainFunction"))).Invoke(); LowLim = ((Func <float>)Delegate.CreateDelegate(typeof(Func <float>), _baseTypeLow.GetMethod("MainFunction"))).Invoke(); } catch (Exception e) { var res = new List <string>(); res.Add(e.Message + ". Stack Trace: " + e.StackTrace); return(res); } } else { var res = new List <string>(); if (compilerResultLow.Errors.Count != 0) { foreach (var a in compilerResultLow.Errors) { var b = a.ToString(); res.Add('/' + b.Substring(b.IndexOf("CS"))); } } if (compilerResultHigh.Errors.Count != 0) { foreach (var a in compilerResultHigh.Errors) { var b = a.ToString(); res.Add('\\' + b.Substring(b.IndexOf("CS"))); } } if (compilerResultPeriod.Errors.Count != 0) { foreach (var a in compilerResultPeriod.Errors) { var b = a.ToString(); res.Add('|' + b.Substring(b.IndexOf("CS"))); } } return(res); } return(null); }