// EventTypeとコンストラクタで渡されたイベントの型が一致していればfuncを実行(EventType変数の引数ありver) public virtual bool Dispatch <EventType>(EventFunction <EventType> func) where EventType : EventBase { if (m_Event.GetType() == typeof(EventType)) { func((EventType)m_Event); return(true); } return(false); }
/// <inheritdoc /> public async Task InvokeHandler(EventBase eventBase, bool isWhileCatchingUp) { if (Cache == null) { await RegisterHandlers(); } try { var key = eventBase.GetType().Name; if (!Cache.ContainsKey(key)) { return; } var methods = Cache[key]; foreach (var method in methods) { InvokeMethod(method, eventBase); } } catch (Exception ex) { _log.LogWarning(ex, "Could not invoke methods for {eventName}", eventBase.Event); } }
protected override void ExecuteDefaultActionAtTarget(EventBase evt) { base.ExecuteDefaultActionAtTarget(evt); //m_ListElementsFactory.Reset(); //evt.StopPropagation(); System.Type type = evt.GetType(); if (type.Name == "SerializedPropertyBindEvent" && type.GetProperty("bindProperty").GetValue(evt) is SerializedProperty property) { m_SerializedObject = property.serializedObject; m_ListPropertyBindingPath = ((ListVisualElement)evt.target).bindingPath; var propertyPath = ListProperty.propertyPath.Split('.'); object baseObject = ListProperty.serializedObject.targetObject; for (int i = 0; i < propertyPath.Length; i++) { baseObject = baseObject.GetType().GetField(propertyPath[i])?.GetValue(baseObject); if (baseObject == null) { return; } } if (baseObject.GetType().IsGenericType) { ListItemType = baseObject.GetType().GetGenericArguments()[0]; } m_ListElementsFactory.Reset(); // Don't allow the binding of `this` to continue because `this` is not // the actually bound field, it is just a container. evt.StopPropagation(); } }
public static bool TryGetPropertyBindEvent(this VisualElement element, EventBase evt, out SerializedProperty property) { property = evt.GetType() == _serializedPropertyBindEventType ? _bindPropertyProperty?.GetValue(evt) as SerializedProperty : null; return(property != null); }
public void Handle(EventBase e) { Type eventType = e.GetType(); if (handlers.ContainsKey(eventType)) { handlers[eventType].Invoke(this, new object[] { e }); } }
protected override void ExecuteDefaultActionAtTarget(EventBase evt) { base.ExecuteDefaultActionAtTarget(evt); switch (evt.GetType().Name) { case "SerializedPropertyBindEvent": break; case "SerializedObjectBindEvent": var bindObjectProperty = evt.GetType().GetProperty("bindObject"); Reset(bindObjectProperty.GetValue(evt) as SerializedObject); break; default: break; } }
public void QueueEvent(EventBase evt) { if (evt == null) { throw new ArgumentNullException("evt"); } WriteQueue.Add(evt); Log.Trace("Queued {0}", evt.GetType().Name); }
public void ApplyEvent(EventBase @event, bool isNew = true) { dynamic thisAsDynamic = this; thisAsDynamic.Handle(Converter.ChangeTo(@event, @event.GetType())); if (isNew) _uncommittedEvents.Add(@event); Version++; }
public void EventHandler(object sender, EventBase evt) { foreach(MovableObjectEvent movEvt in mEventDictionary[evt.GetType()]) { if (movEvt.FromObject != null && sender != movEvt.FromObject) { continue; } TargetObject.GivePath(new List<MovableObjectPosition>(Positions), MoveSpeed, Interruptable, MoveMode, LoopMode); } }
// ReSharper disable once UnusedMember.Global // This is invoked through reflection public void OnEvent(EventBase @event) { Type childType = @event.GetType(); IClientEvent clientEvent = this.options.EventsToHandle.FirstOrDefault(ev => ev.NodeEventType == childType); if (clientEvent == null) { return; } clientEvent.BuildFrom(@event); this.eventsHub.SendToClients(clientEvent).ConfigureAwait(false).GetAwaiter().GetResult(); }
public async Task ProcessAsync(EventBase @event) { var eventType = @event.GetType(); if (!_typeToDenormalizer.ContainsKey(eventType)) { return; } foreach (var handler in _typeToDenormalizer[eventType]) { await handler.HandleAsync(@event); } }
public void Post(EventBase evt) { Type posterType = evt.GetType(); do { if (mHandlers.TryGetValue(posterType, out EventPosterBase handler)) { handler.DeliverEvent(evt); } posterType = posterType.BaseType; }while (posterType != typeof(EventBase)); }
/// <summary> /// Finds applicable subscribers, and has them handle the specified event, on the current thread. /// </summary> /// <param name="evnt">The event to handle.</param> /// <param name="exceptions">Stores exceptions throws by event handlers.</param> protected internal void Handle(EventBase evnt, List <Exception> exceptions) { if (evnt.NullReference()) { throw Exc.Null(nameof(evnt)); } if (exceptions.NullReference()) { throw Exc.Null(nameof(exceptions)); } lock (this.syncLock) { var eventTypeInfo = evnt.GetType().GetTypeInfo(); for (int i = 0; i < this.subscribers.Count;) { var wrapper = this.subscribers[i]; if (EventBase.CanHandle(wrapper.EventHandlerEventTypeInfo, eventTypeInfo)) { bool referenceFound = true; try { wrapper.Handle(evnt, out referenceFound); } catch (Exception ex) { exceptions.Add(ex); } if (referenceFound) { // event handled: continue ++i; } else { // GC already collected the event handler: remove wrapper and continue this.subscribers.RemoveAt(i); } } else { // event handler not compatible with event: continue ++i; } } } }
public void Publish(EventBase @event) { var handlers = this.GetCommandActions(@event.GetType()).ToList(); if (!handlers.Any()) { return; } foreach (var handler in handlers) { var handler1 = handler; handler1.AsDynamic().Handle(@event); ((IDisposable)handler).Dispose(); } }
public async Task PublishAsync(EventBase @event) { var eventName = @event.GetType().Name; var jsonMessage = JsonConvert.SerializeObject(@event); var body = Encoding.UTF8.GetBytes(jsonMessage); var message = new Message { MessageId = Guid.NewGuid().ToString(), Body = body, Label = eventName, SessionId = @event.SessionId }; await _topicClient.SendAsync(message); }
private static string Serialize(EventBase ev) { switch (ev) { case Incremented _: return("i"); case Decremented _: return("d"); case Unchanged u: return($"n {u.Reason}"); default: throw new Exception($"Internal error: unknown type {ev.GetType()}."); } }
public async Task ReactAsync(EventBase @event, CancellationToken cancellationToken) { var context = @event.GetContext(); var reactions = fFactory.Create(@event).ToArray(); if (reactions.Length == 0) { fLogger.LogInformation(context, $"No reaction for event '{@event.GetType()}'"); return; } // TODO: Paralelized reacting foreach (var reaction in reactions) { await reaction.ReactAsync(@event, cancellationToken); } }
public bool HasHandler(EventBase evt) { bool foundReceiver = false; Type posterType = evt.GetType(); do { EventPosterBase handler; if (mHandlers.TryGetValue(posterType, out handler)) { foundReceiver = true; break; } posterType = posterType.BaseType; }while (posterType != typeof(EventBase)); return(foundReceiver); }
public void Post(Component sender, EventBase evt) { #if DEBUG Debug.Log(string.Format("Posting message from {0} : {1} @ {2} - {3}", sender.ToString(), evt.ToString(), evt.Place, evt.Time)); #endif for (Type evtType = evt.GetType(); evtType != typeof(System.Object); evtType = evtType.BaseType) { if (_handlers != null && _handlers.ContainsKey(evtType)) { if (_handlers[evtType] != null) { _handlers[evtType].PostEvt(sender, evt); } else { } } } }
public static DynamicTableEntity ToEntity( this EventBase @event, string partitionkey, long eventVersion) { Ensure.ArgumentNotNull(@event, nameof(@event)); var dte = new DynamicTableEntity(partitionkey, eventVersion.FormatLong()); dte.Properties = new Dictionary <string, EntityProperty>(); dte.Properties.Add(StorageConstants.EventStore.EventType, EntityProperty.GeneratePropertyForString(@event.GetType().AssemblyQualifiedName)); var bytes = Encoding.Default.GetBytes(JsonConvert.SerializeObject(@event)); // var compressed = Brotli.CompressBuffer(bytes, 0, bytes.Length); dte.Properties.Add(StorageConstants.EventStore.EventData, EntityProperty.GeneratePropertyForByteArray(bytes)); return(dte); }
public void TriggerEvent(EventBase evt) { if (evt == null) { throw new ArgumentNullException("evt"); } var type = evt.GetType(); Action <EventBase> listener; if (!m_listeners.TryGetValue(type, out listener) || listener == null) { Log.Debug("Discarding {0}, no listeners", type.Name); return; } Log.Trace("Dispatching {0}", type.Name); listener(evt); }
protected void ApplyEvent(EventBase evt) { List <Type> eventHandlers = EventMapper.GetEventHandlersForEventMessage(evt.GetType()); foreach (var handler in eventHandlers) { var localHandler = handler; Task.Factory.StartNew(() => { var instance = Activator.CreateInstance(localHandler); instance.GetType().InvokeMember("Handle", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, instance, new object[] { evt }); }); } }
public void Publish(EventBase @event) { if (!_persistentConnection.IsConnected) { _persistentConnection.TryConnect(); } var model = JsonConvert.SerializeObject(@event); using (var channel = _persistentConnection.CreateModel()) { channel.ExchangeDeclare(_exchangeName, ExchangeType.Fanout); var body = Encoding.UTF8.GetBytes(model); channel.BasicPublish(_exchangeName, routingKey: @event.GetType().Name, basicProperties: null, body: body); _logger.LogDebug("[x] Sent {0}", model); } }
private void OnSwitchEvent(EventBase theEvent) { EventChannelState e = theEvent as EventChannelState; if (e != null) { EventChannelState channelEvent = theEvent as EventChannelState; if (channelEvent == null) { return; } //OnSwitchEvents(theEvent); ListViewItem item; item = lvAll.Items.Add(channelEvent.ChannelInfo.Address); item.Tag = channelEvent; item.SubItems.Add(channelEvent.Originator.UserName); item.SubItems.Add(channelEvent.UniqueId); item.SubItems.Add(channelEvent.Caller.UniqueId); if (channelEvent.Name == "CHANNEL_STATE") { item.SubItems.Add(e.ChannelInfo.State.ToString()); } else { item.SubItems.Add(e.Name); } if (e.GetType() == typeof(EventCodec) || theEvent.GetType() == typeof(EventChannelExecute) || e.Originator.DestinationNumber == string.Empty) { item.ForeColor = Color.Gray; } } log.Text = theEvent.Name; }
public static void Apply <TAggregate>(TAggregate aggregate, EventBase @event) { var eventApplyMethods = MethodCache.GetOrAdd(aggregate.GetType(), type => { var result = new Dictionary <Type, MethodInfo>(); var eventAppliers = Enumerable.Where <Type>(type .GetInterfaces(), i => i.GetGenericTypeDefinition() == typeof(IEventApplier <>)); foreach (var eventApplier in eventAppliers) { var eventType = eventApplier.GenericTypeArguments.FirstOrDefault(); var applyMethod = eventApplier.GetMethods().FirstOrDefault(); result.Add(eventType, applyMethod); } return(result); }); var suppliedEventType = @event.GetType(); if (!eventApplyMethods.ContainsKey(suppliedEventType)) { return; } eventApplyMethods[suppliedEventType].Invoke(aggregate, new object[] { @event }); }
public IEventHandler GetHandler(EventBase eventBase) { var commandType = eventBase.GetType(); return(_eventHandlerMap.TryGetValue(commandType, out var commandHandler) ? commandHandler : null); }
private async Task HandleEventAsync(EventBase @event) { using (fLogger.TrackRequest(@event.GetContext(), $"SignalR - Authority client event - '{@event.GetType()}'.", out var requestContext)) { try { @event.ChangeContext(requestContext); using var scope = fServiceProvider.CreateScope(); var reactionFacade = scope.ServiceProvider.GetRequiredService <IEventReactionFacade>(); await reactionFacade.ReactAsync(@event, fState.CancellationSource.Token); requestContext.Success(); } catch { requestContext.Fail(); throw; } } }
/// <inheritdoc /> public void Handle(EventBase @event, Exception exception, ISubscription subscription) { this._logger.LogError(exception, "Error handling the event {0}", @event.GetType().Name); throw exception; }
private INotification GetNotificationCorrespondingToDomainEvent(EventBase @event) { return((INotification)Activator.CreateInstance( typeof(EventNotification <>).MakeGenericType(@event.GetType()), @event)); }
public object GetEventHandler(EventBase eventBase, IServiceProvider serviceProvider) => GetEventHandler(eventBase.GetType(), serviceProvider);
internal void Consume(EventBase ev) { typeof(Consumer).GetMethod("Consume", new Type[] { ev.GetType() }).Invoke(this, new object[] { ev }); }
/// <summary> /// Convert command to a string that can be sent to FreeSWITCH /// </summary> /// <returns>FreeSWITCH command</returns> public string ToFreeSwitchString() { var names = _event.GetType().GetEventNames(); return(string.Format("sendevent {0}", names.First())); }