public static EventInfo GetStaticEventInfo(System.Type type, string eventName) { var flags = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; EventInfo ei = type.GetEvent(eventName, flags); while (ei == null && type.BaseType != null) { type = type.BaseType; ei = type.GetEvent(eventName, flags); } return(ei); }
private static void SetMemberValue(object control, Type type, string member, object value) { PropertyInfo propertyInfo = type.GetProperty(member); if (propertyInfo != null) { SetPropertyValue(control, value, propertyInfo); } else { EventInfo eventInfo = type.GetEvent(member); if (eventInfo != null) { switch (eventInfo.EventHandlerType.FullName) { case "System.EventHandler": eventInfo.AddEventHandler(control, new EventHandler((sender, e) => { (value as LuaFunc).Invoke(new LuaValue[] { new LuaUserdata(sender), new LuaUserdata(e) }); })); break; case "System.Windows.Forms.TreeViewEventHandler": eventInfo.AddEventHandler(control, new TreeViewEventHandler((sender, e) => { (value as LuaFunc).Invoke(new LuaValue[] { new LuaUserdata(sender), new LuaUserdata(e) }); })); break; default: throw new NotImplementedException(eventInfo.EventHandlerType.FullName + " type not implemented."); } } } }
private static bool ProcessEventParameters(WorkflowParameterBindingCollection parameters, IMethodMessage message, Type interfaceType, string operation) { bool isKnownSignature = false; if (parameters == null) return isKnownSignature; EventInfo eventInfo = interfaceType.GetEvent(operation); MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke"); int index = 0; foreach (ParameterInfo formalParameter in methodInfo.GetParameters()) { if ((typeof(ExternalDataEventArgs).IsAssignableFrom(formalParameter.ParameterType))) { if (index == 1) isKnownSignature = true; } if (parameters.Contains(formalParameter.Name)) { WorkflowParameterBinding binding = parameters[formalParameter.Name]; binding.Value = message.Args[index]; } index++; } return isKnownSignature; }
private static EventInfo GetEventInfo(Type type, string name) { if ((s_cbmTdpBridge != null) && IsFrameworkType(type)) { Type typeToUseForCBMBridge = GetTypeToUseForCBMBridge(type); if (s_cbmTdpBridge.HasEvent(typeToUseForCBMBridge, name)) { return type.GetEvent(name); } return null; } if (GetReflectionType(type).GetEvent(name) != null) { return type.GetEvent(name); } return null; }
public object Get(string name, object instance, Type type, params object[] arguments) { var ei = type.GetEvent(name, PropertyFilter); if (ei == null) return NoResult; return !CanBind(ei) ? NoResult : ei; //Type eventHelper = typeof(EventHelper<>); //Type actualHelper = eventHelper.MakeGenericType(ei.EventHandlerType); }
public ReflectionEventDescriptor (Type componentType, EventDescriptor oldEventDescriptor, Attribute[] attrs) : base (oldEventDescriptor, attrs) { _componentType = componentType; _eventType = oldEventDescriptor.EventType; EventInfo event_info = componentType.GetEvent (oldEventDescriptor.Name); add_method = event_info.GetAddMethod (); remove_method = event_info.GetRemoveMethod (); }
public ReflectionEventDescriptor (Type componentType, string name, Type type, Attribute[] attrs) : base (name, attrs) { _componentType = componentType; _eventType = type; EventInfo event_info = componentType.GetEvent (name); add_method = event_info.GetAddMethod (); remove_method = event_info.GetRemoveMethod (); }
public object Get(string name, object instance, Type type, params object[] arguments) { EventInfo ei = type.GetEvent(name); if (ei == null) return NoResult; if (!CanBind(ei)) return NoResult; //Type eventHelper = typeof(EventHelper<>); //Type actualHelper = eventHelper.MakeGenericType(ei.EventHandlerType); return ei; }
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 EventInfo FindEvent(Type instanceType, String eventName) { EventInfo info; do { info = instanceType.GetEvent(eventName, NuGenBinding.Instance); instanceType = instanceType.BaseType; } while (info == null && instanceType != _objectType); return info; }
public object Set(string name, object instance, Type type, object value, params object[] arguments) { EventInfo ei = type.GetEvent(name); if (ei == null) return NoResult; if (!CanBind(ei)) return NoResult; if (!(value is RemoveDelegate)) EventHelper.AssignEvent(ei, instance, (IInvokable)value); else EventHelper.RemoveEvent(ei, instance, (IInvokable)value); return value; }
public TeamFoundationHostWrapper(ITeamFoundationContextManager teamFoundationHostObject) { _teamFoundationHostObject = teamFoundationHostObject; _teamFoundationHostObject.ContextChanged += delegate(object sender, ContextChangedEventArgs args) { if (ContextChanged != null) ContextChanged(sender, args); }; _teamFoundationHostObject.ContextChanging += delegate(object sender, ContextChangingEventArgs args) { if (ContextChanging != null) ContextChanging(sender, args); }; _teamFoundationHostObjectType = _teamFoundationHostObject.GetType(); _commandHandlerField = new Lazy<FieldInfo>(() => _teamFoundationHostObjectType.GetField("m_commandHandler", BindingFlags.NonPublic | BindingFlags.Instance)); _promptForServerAndProjectsMethod = new Lazy<MethodInfo>(() => _teamFoundationHostObjectType.GetMethod("PromptForServerAndProjects", BindingFlags.Public | BindingFlags.Instance)); var connectingEventInfo = _teamFoundationHostObjectType.GetEvent("Connecting", BindingFlags.Public | BindingFlags.Instance); var connectingEventHandlerConstructor = connectingEventInfo.EventHandlerType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }); var connectingEventHandler = (Delegate)connectingEventHandlerConstructor.Invoke(new object[] { this, typeof (TeamFoundationHostWrapper).GetMethod("TeamFoundationHostConnecting", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle.GetFunctionPointer() }); connectingEventInfo.AddEventHandler(_teamFoundationHostObject, connectingEventHandler); var connectionCompletedEventInfo = _teamFoundationHostObjectType.GetEvent("ConnectionCompleted", BindingFlags.Public | BindingFlags.Instance); var connectionCompletedEventHandlerConstructor = connectionCompletedEventInfo.EventHandlerType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }); var connectionCompletedEventHandler = (Delegate)connectionCompletedEventHandlerConstructor.Invoke(new object[] { this, typeof (TeamFoundationHostWrapper).GetMethod("TeamFoundationHostConnectionCompleted", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle.GetFunctionPointer() }); connectionCompletedEventInfo.AddEventHandler(_teamFoundationHostObject, connectionCompletedEventHandler); }
private static void WireToDefaultEvent(Parameter parameter, Type type, DependencyObject source, PropertyInfo property) { var defaults = IoC.Get<IConventionManager>() .GetElementConvention(type); if (defaults == null) throw new CaliburnException( "Insuficient information provided for wiring action parameters. Please set interaction defaults for " + type.FullName ); var eventInfo = type.GetEvent(defaults.EventName); if (property == null) parameter.Wire(source, eventInfo, () => defaults.GetValue(source)); else parameter.Wire(source, eventInfo, () => property.GetValue(source, null)); }
void SetNON2008R2ObjectExplorerEventProvider(System.Type t) { // the old way of doing things //IObjectExplorerEventProvider objectExplorer = (IObjectExplorerEventProvider)Common.ObjectExplorerService.GetService(typeof(IObjectExplorerEventProvider)); //objectExplorer.SelectionChanged += new NodesChangedEventHandler(objectExplorer_SelectionChanged); MethodInfo mi = this.GetType().GetMethod("Provider_SelectionChanged", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); // get the IObjectExplorerEventProvider from the ObjectExplorerService object objectExplorer = Connect.ObjectExplorer.GetService(t); EventInfo ei = t.GetEvent("SelectionChanged", System.Reflection.BindingFlags.Public | BindingFlags.Instance); // use this overload CreateDelegate(Type type, object firstArgument, MethodInfo method); // the 2nd param is "this" because the method to handle the event is in it. Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi); ei.AddEventHandler(objectExplorer, del); }
static EventInfo FindEvent (Type wrapperType, Type objectType, string name) { EventInfo info; if (wrapperType != null) { info = wrapperType.GetEvent (name, flags); if (info != null) return info; } info = objectType.GetEvent (name, flags); if (info != null) return info; throw new ArgumentException ("Invalid event name " + objectType.Name + "." + name); }
public ReflectionHelper(Type workItemTestType) { enqueueWorkItemMethod = workItemTestType.GetMethod("EnqueueWorkItem"); unitTestHarnessProperty = workItemTestType.GetProperty("UnitTestHarness"); var unitTestHarnessType = unitTestHarnessProperty.PropertyType; dispatcherStackProperty = unitTestHarnessType.GetProperty("DispatcherStack"); var dispatcherStackType = dispatcherStackProperty.PropertyType; pushWorkItemMethod = dispatcherStackType.GetMethod("Push"); popWorkItemMethod = dispatcherStackType.GetMethod("Pop"); compositeWorkItemType = pushWorkItemMethod.GetParameters()[0].ParameterType; compositeWorkItemExceptionEvent = compositeWorkItemType.GetEvent("UnhandledException"); }
private static bool ProcessEventParameters(WorkflowParameterBindingCollection parameters, IMethodMessage message, Type interfaceType, string operation) { bool flag = false; if (parameters != null) { MethodInfo method = interfaceType.GetEvent(operation).EventHandlerType.GetMethod("Invoke"); int index = 0; foreach (ParameterInfo info3 in method.GetParameters()) { if (typeof(ExternalDataEventArgs).IsAssignableFrom(info3.ParameterType) && (index == 1)) { flag = true; } if (parameters.Contains(info3.Name)) { WorkflowParameterBinding binding = parameters[info3.Name]; binding.Value = message.Args[index]; } index++; } } return flag; }
private static EventInfo findEventInfo(PlTerm memberSpec, Type c, ref Type[] paramz, BindingFlags searchFlags) { if (memberSpec.IsVar) { WarnMissing("findEventInfo IsVar {0} on type {1}", memberSpec, c); return null; } if (memberSpec.IsInteger) { int ordinal = memberSpec.intValue(); var mis = c.GetEvents(BindingFlagsALL); if (ordinal < 0 || ordinal >= mis.Length) return null; return mis[ordinal]; } if (IsTaggedObject(memberSpec)) { var r = tag_to_object(memberSpec[1].Name) as EventInfo; if (r != null) return r; } if (memberSpec.IsCompound) { if (memberSpec.Name == "e") { var arg1 = memberSpec.Arg(0); if (arg1.IsInteger) { Type[] paramzN = null; return findEventInfo(arg1, c, ref paramzN, searchFlags); } } } if (c == null) return null; EventInfo ei = c.GetEvent(memberSpec.Name, searchFlags); if (ei != null) return ei; var members = c.GetEvents(searchFlags); if (members.Length == 0) return null; int arity = (paramz != null) ? paramz.Length : memberSpec.Arity; EventInfo candidate = null; foreach (var info in members) { var infos = info.GetRaiseMethod(); ParameterInfo[] paramTypes = infos.GetParameters(); if (paramTypes.Length == arity) { if (ParamsMatch(paramz, paramTypes)) return info; if (infos.IsStatic) { if (candidate == null) { candidate = info; } } else { if (candidate == null) { candidate = info; } } } } return candidate ?? members[0]; }
/// <summary> /// Determines whether the specified target is a dependency property, routed event, or standard property/event. /// </summary> private static UvmlMutatorTarget GetMutatorTarget(UltravioletContext uv, String name, String value, Type type, out Object target, out Type targetType) { var upf = uv.GetUI().GetPresentationFoundation(); // If this is an attached property/event, find the owner type. var depname = new DependencyName(name); if (depname.IsAttached) { var attachedOwnerType = default(Type); if (!upf.GetKnownType(depname.Owner, out attachedOwnerType)) throw new UvmlException(PresentationStrings.UnrecognizedType.Format(depname.Owner)); type = attachedOwnerType; } // Is it a dependency property? var dprop = DependencyProperty.FindByName(depname.Name, type); if (dprop != null) { target = dprop; if (value != null && BindingExpressions.IsBindingExpression(value)) { targetType = typeof(String); return UvmlMutatorTarget.DependencyPropertyBinding; } targetType = dprop.PropertyType; return UvmlMutatorTarget.DependencyProperty; } // Is it a routed event? var revt = EventManager.FindByName(depname.Name, type); if (revt != null) { target = revt; targetType = typeof(String); return UvmlMutatorTarget.RoutedEvent; } // Is it a standard property? var clrprop = type.GetProperty(depname.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (clrprop != null) { target = clrprop; targetType = clrprop.PropertyType; return UvmlMutatorTarget.StandardProperty; } // Is it a standard event? var clrevt = type.GetEvent(depname.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (clrevt != null) { target = clrevt; targetType = typeof(String); return UvmlMutatorTarget.StandardEvent; } throw new UvmlException(PresentationStrings.EventOrPropertyDoesNotExist.Format(depname.Name, type.Name)); }
bool parsedAsEventProperty(Type currentType, string eventName) { EventInfo evt = currentType.GetEvent(eventName); if (evt == null) return false; nodeQueue.Add(new XamlClrEventNode( reader.LineNumber, reader.LinePosition, getDepth(), eventName, evt, reader.Value)); // writer.CreateEvent(evt); // writer.CreateEventDelegate(reader.Value, evt.EventHandlerType); // writer.EndEvent(); return true; }
internal Button(object realButton, Type iButtonType, Type functionVisibilityType) { this.realButton = realButton; this.functionVisibilityType = functionVisibilityType; textProperty = iButtonType.GetProperty("Text", BindingFlags.Public | BindingFlags.Instance); textColorProperty = iButtonType.GetProperty("TextColor", BindingFlags.Public | BindingFlags.Instance); texturePathProperty = iButtonType.GetProperty("TexturePath", BindingFlags.Public | BindingFlags.Instance); toolTipProperty = iButtonType.GetProperty("ToolTip", BindingFlags.Public | BindingFlags.Instance); visibleProperty = iButtonType.GetProperty("Visible", BindingFlags.Public | BindingFlags.Instance); visibilityProperty = iButtonType.GetProperty("Visibility", BindingFlags.Public | BindingFlags.Instance); effectivelyVisibleProperty = iButtonType.GetProperty("EffectivelyVisible", BindingFlags.Public | BindingFlags.Instance); enabledProperty = iButtonType.GetProperty("Enabled", BindingFlags.Public | BindingFlags.Instance); importantProperty = iButtonType.GetProperty("Important", BindingFlags.Public | BindingFlags.Instance); onClickEvent = iButtonType.GetEvent("OnClick", BindingFlags.Public | BindingFlags.Instance); onMouseEnterEvent = iButtonType.GetEvent("OnMouseEnter", BindingFlags.Public | BindingFlags.Instance); onMouseLeaveEvent = iButtonType.GetEvent("OnMouseLeave", BindingFlags.Public | BindingFlags.Instance); destroyMethod = iButtonType.GetMethod("Destroy", BindingFlags.Public | BindingFlags.Instance); realClickHandler = attachEventHandler(onClickEvent, "clicked", realButton); realMouseEnterHandler = attachEventHandler(onMouseEnterEvent, "mouseEntered", realButton); realMouseLeaveHandler = attachEventHandler(onMouseLeaveEvent, "mouseLeft", realButton); }
private Dictionary<string, EventHandlerInfo> GetPropertyChangedEvents(Type itemType) { if (itemType == null) throw new ArgumentNullException("itemType"); Dictionary<string, EventHandlerInfo> events = new Dictionary<string, EventHandlerInfo>(); foreach (PropertyInfo prop in itemType.GetProperties()) { EventInfo propChangedEvent = itemType.GetEvent(prop.Name + "Changed"); if (propChangedEvent != null && propChangedEvent.EventHandlerType == typeof(EventHandler)) { EventHandler handler = delegate(object sender, EventArgs args) { this.OnItemChanged(list.IndexOf(sender), prop.Name); this.RaiseEvents(); }; events.Add(prop.Name, new EventHandlerInfo(propChangedEvent, handler)); } } return events; }
public void StopListening(Type type) { string eventName = _propertyName + "Changed"; EventInfo eventInfo = type.GetEvent(eventName, BindingFlags.Public | BindingFlags.Static); if (eventInfo != null) { Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, OnStaticPropertyChangedMethodInfo); eventInfo.RemoveEventHandler(null, d); } }
public void BuildEventTest(Type parentType, Type declaringType, Type classType) { // Arrange var typeBuilder = _proxyTypeBuilderFactory.CreateBuilder(parentType); if (declaringType.IsInterface) typeBuilder.AddInterface(declaringType); var eventInfo = declaringType.GetEvents(BindingFlags.Instance | BindingFlags.Public).Single(); Assert.That(eventInfo, Is.Not.Null); // Act typeBuilder.BuildEvent(eventInfo); var type = typeBuilder.CreateType(); // Assert Assert.DoesNotThrow(() => Activator.CreateInstance(type)); foreach (var interfaceType in declaringType.GetInterfaces()) { Assert.That(interfaceType.IsAssignableFrom(type), Is.True); } Assert.That(parentType.IsAssignableFrom(type), Is.True); Assert.That(declaringType.IsAssignableFrom(type), Is.True); var isExplicit = declaringType.IsInterface; EventInfo actual; if (isExplicit) actual = type.GetEvent(eventInfo.GetFullName(), BindingFlags.NonPublic | BindingFlags.Instance); else actual = type.GetEvent(eventInfo.Name); var expected = classType.GetEvent(eventInfo.Name); MemberAssert.AreEquivalent(actual, expected, isExplicit); }
/// <summary> /// Helper method to get an event on an owner, walking up the class hierarchy /// when doing so /// </summary> /// <param name="owner">Type we should look for the event on</param> /// <param name="eventName">Then name of the handler of the event</param> /// <returns>EventInfo for resolved event</returns> internal EventInfo GetClrEventInfo( Type owner, string eventName) { Debug.Assert(null != eventName, "null eventName"); Debug.Assert(null != owner, "null owner"); EventInfo eventInfo = null; // Look up the parent chain until we find a match or fail by // going off the top of the chain. while (owner != null) { eventInfo = owner.GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public); if (eventInfo != null) { break; } owner = GetCachedBaseType(owner); } return eventInfo; }
private static void AddNewProperties(List <CustomProperty> propCollection, System.Type customActivityType, IServiceProvider serviceProvider, List <CustomProperty> existingProps) { IMemberCreationService service = serviceProvider.GetService(typeof(IMemberCreationService)) as IMemberCreationService; if (service == null) { throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName })); } ITypeProvider provider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider; if (provider == null) { throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName })); } foreach (CustomProperty property in propCollection) { bool flag = (property.oldPropertyName == null) || (property.oldPropertyType == null); if (!flag) { if (!property.IsEvent) { flag = customActivityType.GetProperty(property.oldPropertyName, provider.GetType(property.oldPropertyType)) == null; } else { flag = customActivityType.GetEvent(property.oldPropertyName) == null; } } if (flag) { AttributeInfo[] attributes = CreateCustomPropertyAttributeArray(property, serviceProvider); if (property.IsEvent) { service.CreateEvent(customActivityType.FullName, property.Name, provider.GetType(property.Type), attributes, property.GenerateDependencyProperty); } else { service.CreateProperty(customActivityType.FullName, property.Name, provider.GetType(property.Type), attributes, property.GenerateDependencyProperty, false, false, null, false); } } else { CustomProperty oldProperty = null; foreach (CustomProperty property3 in existingProps) { if ((property3.Name == property.oldPropertyName) && (property3.Type == property.oldPropertyType)) { oldProperty = property3; } } if ((oldProperty == null) || ArePropertiesDifferent(property, oldProperty)) { AttributeInfo[] infoArray2 = CreateCustomPropertyAttributeArray(property, serviceProvider); CreateCustomPropertyAttributeArray(oldProperty, serviceProvider); System.Type newEventType = provider.GetType(property.Type, false); System.Type type = provider.GetType(property.oldPropertyType, false); if (newEventType != null) { if (property.IsEvent) { service.UpdateEvent(customActivityType.FullName, property.oldPropertyName, type, property.Name, newEventType, infoArray2, property.GenerateDependencyProperty, false); } else { service.UpdateProperty(customActivityType.FullName, property.oldPropertyName, type, property.Name, newEventType, infoArray2, property.GenerateDependencyProperty, false); } } } } } }
/// <summary>Deregisters a static event from the target type. </summary> /// <param name="type">The target type. </param> /// <param name="eventName">The event name. </param> /// <param name="token">The registration token. </param> public static void DeregisterStaticEvent(Type type, string eventName, object token) { var eventInfo = type.GetEvent(eventName); eventInfo.GetRemoveMethod().Invoke(null, new object[] { token }); }
private static EventInfo FindEvent(BindingFlags f, Type clazz, string pname) { EventInfo property = clazz.GetEvent(pname, f); if (property != null) { return property; } foreach (Type ifc in clazz.GetInterfaces()) { property = FindEvent(f, ifc, pname); if (property != null) { return property; } } if (!clazz.IsInterface && clazz.BaseType == typeof(object)) { property = FindEvent(f, clazz.BaseType, pname); if (property != null) { return property; } } return null; }
private bool TryGetClrEvent(Type/*!*/ type, BindingFlags bindingFlags, string/*!*/ name, out RubyMemberInfo method) { Assert.NotNull(type, name); EventInfo eventInfo = type.GetEvent(name, bindingFlags); if (eventInfo != null) { // creates detached info if only declared members are requested (used by Kernel#clr_member): bool createDetached = (bindingFlags & BindingFlags.DeclaredOnly) != 0; method = new RubyEventInfo((EventTracker)MemberTracker.FromMemberInfo(eventInfo), RubyMemberFlags.Public, this, createDetached); return true; } method = null; return false; }
public LuaCSFunction GetEventWrap(Type type, string eventName) { if (!methodsCache.ContainsKey(type)) { methodsCache[type] = new Dictionary<string, LuaCSFunction>(); } var methodsOfType = methodsCache[type]; if (!methodsOfType.ContainsKey(eventName)) { { EventInfo eventInfo = type.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static); if (eventInfo == null) { throw new Exception(type.Name + " has no event named: " + eventName); } int start_idx = 0; MethodInfo add = eventInfo.GetAddMethod(); MethodInfo remove = eventInfo.GetRemoveMethod(); bool is_static = add != null ? add.IsStatic : remove.IsStatic; if (!is_static) start_idx = 1; methodsOfType[eventName] = (L) => { object obj = null; if (!is_static) { obj = translator.GetObject(L, 1, type); if (obj == null) { return LuaAPI.luaL_error(L, "invalid #1, needed:" + type); } } try { Delegate handlerDelegate = translator.CreateDelegateBridge(L, eventInfo.EventHandlerType, start_idx + 2); if (handlerDelegate == null) { return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 2) + ", needed:" + eventInfo.EventHandlerType); } switch (LuaAPI.lua_tostring(L, start_idx + 1)) { case "+": if (add == null) { return LuaAPI.luaL_error(L, "no add for event " + eventName); } add.Invoke(obj, new object[] { handlerDelegate }); break; case "-": if (remove == null) { return LuaAPI.luaL_error(L, "no remove for event " + eventName); } remove.Invoke(obj, new object[] { handlerDelegate }); break; default: return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 1) + ", needed: '+' or '-'" + eventInfo.EventHandlerType); } } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception:" + e + ",stack:" + e.StackTrace); } return 0; }; } } return methodsOfType[eventName]; }
public void FakeEvent(Object target, String infoName, params object[] parameters) { Type type = target.GetType(); EventInfo eventInfo = type.GetEvent(infoName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); MethodInfo m = null; if (eventInfo != null) { infoName = eventInfo.Name; m = eventInfo.GetRaiseMethod(true); } Exception lastException = null; if (m != null) { try { m.Invoke(target, parameters); return; } catch (Exception e) { lastException = e; } } else { { foreach (var o in new[] { "", "_", "m_" }) { FieldInfo fieldInfo = type.GetField(o + infoName, BindingFlags.Instance | BindingFlags.NonPublic) ?? type.GetField(o + infoName, BindingFlags.Instance | BindingFlags.Public) ?? type.GetField(o + infoName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); if (fieldInfo != null) { Delegate del = fieldInfo.GetValue(target) as Delegate; if (del != null) { del.DynamicInvoke(parameters); return; } } } } if (eventInfo != null) { m = eventInfo.EventHandlerType.GetMethod("Invoke"); if (m != null) { Type dt = m.DeclaringType; try { m.Invoke(target, parameters); return; } catch (Exception e) { lastException = e; } } } var ms = eventInfo.GetOtherMethods(true); foreach (MethodInfo info in ms) { } } if (lastException != null) { throw lastException; } //MethodInfo m = eventInfo.GetOtherMethods(true); throw new NotSupportedException(); }
internal static EventInfo getEvent(Type type, string name) { return type.GetEvent(name, BindingFlags.Public | BindingFlags.Instance); }
/// <summary> /// Draw the GUI. /// </summary> public override void OnInspectorGUI() { myTarget = (EventResponder)target; Undo.RecordObject(target, "Event Update"); GameObject sender = (GameObject)EditorGUILayout.ObjectField(new GUIContent("Sender", "Add the Game Object that holds the target component."), myTarget.sender, typeof(GameObject), true); myTarget.sender = sender; if (myTarget.sender != null) { types = GetComponentsOnGameObject(myTarget.sender); } if (myTarget.sender == null) { myTarget.sender = myTarget.gameObject; } if (myTarget.sender != null) { string typeName = null; if (types == null) { types = GetComponentsOnGameObject(myTarget.sender); } int typeIndex = System.Array.IndexOf(types, myTarget.typeName); if (typeIndex == -1 || typeIndex >= types.Length) { typeIndex = 0; } if (types != null && types.Length > 0) { typeName = types[EditorGUILayout.Popup("Component", typeIndex, types)]; } else { EditorGUILayout.HelpBox("No components found on this GameObject.", MessageType.Info); } myTarget.typeName = typeName; if (myTarget.typeName != null && myTarget.typeName.Length > 0) { events = GetEventNamesForType(myTarget.typeName); if (events != null && events.Length > 0) { int eventIndex = System.Array.IndexOf(events, myTarget.eventName); if (eventIndex == -1 || eventIndex >= events.Length) { eventIndex = 0; } string name = events[EditorGUILayout.Popup("Event", eventIndex, events)]; myTarget.eventName = name; type = typeof(Character).Assembly.GetType("PlatformerPro." + typeName); if (type == null) { type = typeof(Character).Assembly.GetTypes().Where(t => t.Name == typeName).FirstOrDefault(); } eventInfo = type.GetEvent(myTarget.eventName); parameterType = eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters()[1].ParameterType; // Animation event if (parameterType != null && parameterType.IsAssignableFrom(typeof(AnimationEventArgs))) { myTarget.animationStateFilter = (AnimationState)EditorGUILayout.EnumPopup(new GUIContent("Animation State", "The animation state which will trigger this event response, use NONE for any state"), myTarget.animationStateFilter); } // Damage event if (parameterType != null && parameterType.IsAssignableFrom(typeof(DamageInfoEventArgs))) { myTarget.damageTypeFilter = (DamageType)EditorGUILayout.EnumPopup(new GUIContent("Damage Type", "The damage type which will trigger this event response, use NONE for any type"), myTarget.damageTypeFilter); } // Button event if (parameterType != null && parameterType.IsAssignableFrom(typeof(ButtonEventArgs))) { myTarget.buttonStateFilter = (ButtonState)EditorGUILayout.EnumPopup(new GUIContent("Button State", "The button state which triggers this response, use ANY for any type"), myTarget.buttonStateFilter); } // Phase event if (parameterType != null && parameterType.IsAssignableFrom(typeof(PhaseEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("Phase", "Name of the phase or empty string for any phase."), myTarget.stringFilter); } // State event if (parameterType != null && parameterType.IsAssignableFrom(typeof(StateEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("State", "Name of the state or empty string for any state."), myTarget.stringFilter); } // Attack event if (parameterType != null && parameterType.IsAssignableFrom(typeof(AttackEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("Attack", "Name of the attack or empty string for any attack."), myTarget.stringFilter); } // Extra Damage event if (parameterType != null && parameterType.IsAssignableFrom(typeof(ExtraDamageInfoEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("Attack", "Name of the attack or empty string for any attack."), myTarget.stringFilter); } // Item event if (parameterType != null && parameterType.IsAssignableFrom(typeof(ItemEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("Item Type", "Name of the item type or empty for any item."), myTarget.stringFilter); myTarget.intFilter = EditorGUILayout.IntField(new GUIContent("Amount", "Minimum amount that must be in the inventory."), myTarget.intFilter); } // Activation event if (parameterType != null && parameterType.IsAssignableFrom(typeof(ActivationEventArgs))) { myTarget.stringFilter = EditorGUILayout.TextField(new GUIContent("Item", "Name of the Activation Item or empty string for any item."), myTarget.stringFilter); } } else { EditorGUILayout.HelpBox("No events found on this component.", MessageType.Info); } } } if (myTarget.actions != null) { for (int i = 0; i < myTarget.actions.Length; i++) { EditorGUILayout.BeginVertical("HelpBox"); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (i == 0) { GUI.enabled = false; } if (GUILayout.Button("Move Up", EditorStyles.miniButtonLeft)) { EventResponse tmp = myTarget.actions[i - 1]; myTarget.actions[i - 1] = myTarget.actions[i]; myTarget.actions[i] = tmp; break; } GUI.enabled = true; if (i == myTarget.actions.Length - 1) { GUI.enabled = false; } if (GUILayout.Button("Move Down", EditorStyles.miniButtonRight)) { EventResponse tmp = myTarget.actions[i + 1]; myTarget.actions[i + 1] = myTarget.actions[i]; myTarget.actions[i] = tmp; break; } GUI.enabled = true; // Remove GUILayout.Space(4); bool removed = false; if (GUILayout.Button("Remove", EditorStyles.miniButton)) { myTarget.actions = myTarget.actions.Where(a => a != myTarget.actions[i]).ToArray(); removed = true; } GUILayout.EndHorizontal(); if (!removed) { RenderAction(myTarget, myTarget, myTarget.actions[i]); } EditorGUILayout.EndVertical(); } } EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); // Add new actions if (GUILayout.Button("Add Action")) { if (myTarget.actions == null) { myTarget.actions = new EventResponse[1]; } else { // Copy and grow array EventResponse[] tmpActions = myTarget.actions; myTarget.actions = new EventResponse[tmpActions.Length + 1]; System.Array.Copy(tmpActions, myTarget.actions, tmpActions.Length); } } EditorGUILayout.EndHorizontal(); }
/// <summary>Registers a static event on the given target object. </summary> /// <param name="type">The target type. </param> /// <param name="eventName">The event name. </param> /// <param name="callback">The callback. </param> /// <returns>The registration token to deregister the event. </returns> public static object RegisterStaticEvent(Type type, string eventName, Action<object, object> callback) { var callbackMethodInfo = callback.Method; var eventInfo = type.GetEvent(eventName); var callbackDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, callback.Target, callbackMethodInfo); return eventInfo.GetAddMethod().Invoke(null, new object[] { callbackDelegate }); }
/// <summary> /// Erzeugt den Typen für einen dynamischen Draht für ein bestimmtes Ereignis einer Komponente. /// </summary> /// <param name="componentType">Typ der Komponente</param> /// <param name="eventMemberName">Name des Ereignisses oder der Delegat-Eigenschaft</param> /// <param name="isEvent">Gibt an, ob der Draht als Ereignis implementiert ist, oder nicht</param> /// <returns>Typ des dynamischen Drahts</returns> private Type BuildDynamicWireType(Type componentType,string eventMemberName, bool isEvent) { // Verweise der Komponenten-Assembly übernehmen string[] references = (from assy in componentType.Assembly.GetReferencedAssemblies() select Assembly.Load(assy).Location).ToArray(); // Variable für Quellcode string sourceCode = string.Empty; // Wenn der Draht als Ereignis implementiert ist ... if (isEvent) { // Metadaten des Ereignisses abrufen EventInfo eventInfo = componentType.GetEvent(eventMemberName); // Quellcode für dynamischen Draht erzeugen sourceCode = CreateDynamicWireSourceCodeForEvent(eventInfo); } else { // Metadaten der Delegat-Eigenschaft abrufen PropertyInfo delegatePropInfo = componentType.GetProperty(eventMemberName); // Quellcode für dynamischen Draht erzeugen sourceCode = CreateDynamicWireSourceCodeForDelegate(delegatePropInfo); } // Dynamischen Draht kompilieren Assembly assembly = ScriptEngine.CompileScriptToAssembly(sourceCode, references); // Typinformationen des dynamischen Drahtes abrufen Type dynamicWireType = assembly.GetType("Zyan.Communication.DynamicWire"); // Typ des dynamischen Drahtes zurückgeben return dynamicWireType; }