コード例 #1
0
        public void Send(IEvent @event)
        {
            var eventType = @event.GetType();
            var eventTypes = new List<Type>{ eventType };

            var baseEventType = eventType.BaseType;

            while (baseEventType != null && typeof(IEvent).IsAssignableFrom(baseEventType))
            {
                eventTypes.Add(baseEventType);
                baseEventType = baseEventType.BaseType;
            }

            foreach (var @interface in eventType.GetInterfaces())
            {
                if (typeof(IEvent).IsAssignableFrom(@interface))
                {
                    eventTypes.Add(@interface);
                }
            }

            foreach (var type in eventTypes)
            {
                var handlers = FindDirectHandlers(type);
                InvokeHandlers(@event, handlers);
            }
        }
コード例 #2
0
ファイル: DisableDrunkEffect.cs プロジェクト: Archanium/ngj
    public bool HandleEvent(IEvent @event)
    {
        //Debug.LogWarning("change scene event");

        var sceneChangeEvent = @event as SceneChangeEvent;
        if (sceneChangeEvent == null)
        {
            Debug.LogError("SceneChangeEvent is null");
            return true;
        }

        var data = @event.GetData() as string;
        if (data == null)
        {
            Debug.LogError("data is null");
            return true;
        }

        try
        {
            this.currentScene = (SceneNames)Enum.Parse(typeof(SceneNames), data, ignoreCase: true);
            //Debug.LogWarning("change scene to " + this.currentScene );
        }
        catch
        {
            //Debug.Log("unable to parse");
            // do nothing
        }

        return true;
    }
コード例 #3
0
 public void EmulatorStarted(IEvent e)
 {
     foreach (var a in _gameStartedActions)
     {
         a.Invoke();
     }
 }
コード例 #4
0
        private void InvokeHandlers(IEvent @event, IEnumerable<HandlerMethod> handlers)
        {
            foreach (var method in handlers)
            {
                object handler;

                try
                {
                    handler = HandlerActivator.CreateInstance(method.ReflectedType);
                }
                catch (Exception ex)
                {
                    throw new EventHandlerException("Fail to activate event handler: " + method.ReflectedType + ". See inner exception for details.", ex);
                }

                try
                {
                    method.Invoke(handler, @event);
                }
                catch (Exception ex)
                {
                    throw new EventHandlerException("Fail to execute event handler: " + method.ReflectedType + ". See inner exception for details.", ex);
                }
            }
        }
コード例 #5
0
 public void EmulatorQuit(IEvent e)
 {
     foreach (var a in _gameEndedActions)
     {
         a.Invoke();
     }
 }
コード例 #6
0
 public ICompletionData CreateEventCreationCompletionData(string varName, IType delegateType, IEvent evt,
                                                          string parameterDefinition,
                                                          IUnresolvedMember currentMember,
                                                          IUnresolvedTypeDefinition currentType)
 {
     return new CompletionData(varName);
 }
コード例 #7
0
        public void FireEvent(
			IEvent @event)
        {
            string namespaceUri = @event.NamespaceUri;
            string eventType = @event.Type;
            for (int i = 0; i < count; i++)
            {
            // Check if the entry was added during this phase
            if (entries[i].Locked)
              continue;

                string entryNamespaceUri = entries[i].NamespaceUri;
                string entryEventType = entries[i].Type;

                if (entryNamespaceUri != null && namespaceUri != null)
                {
                    if (entryNamespaceUri != namespaceUri)
                    {
                        continue;
                    }
                }

                if (entryEventType != eventType)
                {
                    continue;
                }

                entries[i].Listener(@event);
            }
        }
コード例 #8
0
        /// <summary>
        /// Appends an event to the uncommitted event stream, setting the correct EventSourceId and Sequence Number for the event.
        /// </summary>
        /// <param name="event">The event to be appended.</param>
        public void Append(IEvent @event)
        {
            EnsureEventCanBeAppendedToThisEventSource(@event);
            AttachAndSequenceEvent(@event);

            Events.Add(@event);
        }
コード例 #9
0
		/// <summary>
		/// Copy constructor
		/// </summary>
		protected DefaultEvent(IEvent ev)
			: base(ev)
		{
			this.addAccessor = ev.AddAccessor;
			this.removeAccessor = ev.RemoveAccessor;
			this.invokeAccessor = ev.InvokeAccessor;
		}
コード例 #10
0
ファイル: TcpHost.cs プロジェクト: anjing/TCPChannel
 public void HandleEvent(IProtocol protocol, IEvent e)
 {
     EventId eid = (EventId)e.ID;
     switch (eid)
     {
         case EventId.Disconnect:
             Stop();
             break;
         case EventId.SendMessage:
             if (!protocol.isClosed())
             {
                 if (transport != null)
                 {
                     transport.Send(e.Data);
                 }
             }
             break;
         case EventId.Media:
             Console.WriteLine("media event received, id={0}", eid);
             break;
         case EventId.Content:
             break;
         case EventId.Stack:
             break;
         case EventId.Schedule:
             break;
     }
 }
コード例 #11
0
        /// <summary>
        /// Tries to parse the given data to the target <see cref="IEvent"/>.
        /// </summary>
        /// <param name="eventParams">List of string-parameters to parse.</param>
        /// <param name="target">Target instance to parse the data to.</param>
        /// <returns><c>true</c> if the parsing was succesful, otherwise <c>false</c> is returned.</returns>
        public bool TryParse(List<string> eventParams, IEvent target)
        {
            if (eventParams.Count < 4)
            {
                return false;
            }

            if (string.IsNullOrEmpty(eventParams[0]))
            {
                return false;
            }

            float posX, posY, posZ;
            if( !float.TryParse(eventParams[1], out posX) ||
                !float.TryParse(eventParams[2], out posY) ||
                !float.TryParse(eventParams[3], out posZ) )
            {
                return false;
            }

            if (!target.HasProperty("EntityName") || !target.HasProperty("Target"))
            {
                return false;
            }

            UnityEngine.Vector3 targetPosition = new UnityEngine.Vector3();
            targetPosition.x = posX;
            targetPosition.y = posY;
            targetPosition.z = posZ;

            target.SetProperty("EntityName", eventParams[0]);
            target.SetProperty("Target", targetPosition);
            return true;
        }
コード例 #12
0
 public void Execute(IEvent eEvent)
 {
     if (UserSettings.Instance.IsFirstRun())
     {
         Plugin.Instance.OpenInfoWindow();
     }
 }
コード例 #13
0
    /// <summary>
    /// This method will handle sending an event to a client.
    /// </summary>
    public static void SendEventToClient(string ipAddress, int port, IEvent evnt)
    {
      try
      {
        var client = new TcpClient(ipAddress, port);

        // TODO: Serialize the event into json...
        string json = JsonConvert.SerializeObject(evnt);
        byte[] data = System.Text.Encoding.Unicode.GetBytes(json);

        // Get a client stream for reading and writing.
        var stream = client.GetStream();
        stream.Write(data, 0, data.Length);

        Console.WriteLine("Sent: {0}", json);

        // Close everything.
        stream.Close();
        client.Close();
      }
      catch (ArgumentNullException e)
      {
        Console.WriteLine("ArgumentNullException: {0}", e);
      }
      catch (SocketException e)
      {
        Console.WriteLine("SocketException: {0}", e);
      }
    }
コード例 #14
0
 public void ProcessEvent(IEvent Event)
 {
     lock (_milliSeconds)
     {
         //_milliSeconds.Enqueue(DateTime.Now.Subtract(((InboundConnectionClosedEvent)Event).StartTime).TotalMilliseconds);
     }
 }
コード例 #15
0
ファイル: CompositeEventBus.cs プロジェクト: HAXEN/ncqrs
 public void Publish(IEvent eventMessage)
 {
     foreach (var bus in _wrappedBuses)
     {
         bus.Publish(eventMessage);
     }
 }
コード例 #16
0
        protected IEnumerable<IPipelet> RebuildPipeline(IEvent @event)
        {
            log.InfoFormat("Rebuilding pipeline for event {0}", @event.GetType());

            var rebuildPipeline = pipelets.Where(p => p.WantsEvent(@event)).ToList();
            return rebuildPipeline;
        }
コード例 #17
0
ファイル: Event.cs プロジェクト: haleox/mortar
        /// <summary>
        /// Gets a string of all data properties of the passed <see cref="IEvent"/>.
        /// Format-Example: Name0: Value0, ..., NameN: ValueN
        /// </summary>
        /// <param name="e"><see cref="IEvent"/> to create data string from.</param>
        /// <returns>String representing the <see cref="IEvent"/> data.</returns>
        public static string GetEventDataAsString(IEvent e)
        {
            string data = "";

            if (e != null)
            {
                int i = 0;
                foreach (PropertyInfo property in e.GetType().GetProperties())
                {
                    if (GetNamesOfProperties().Contains(property.Name))
                    {
                        continue;
                    }

                    if (i > 0)
                    {
                        data += ", ";
                    }
                    data += string.Format("{0}: {1}", property.Name, property.GetValue(e, null));
                    i++;
                }
            }

            return data;
        }
コード例 #18
0
        public CalendarEvent(IEvent serverEvent)
        {
            IsLastItem = false;
            IsFirstItem = false;

            string bodyContent = string.Empty;
            if (serverEvent.Body != null)
                bodyContent = serverEvent.Body.Content;

            ID = serverEvent.Id;
            Subject = serverEvent.Subject;
            Location = serverEvent.Location.DisplayName;
            StartDate = (DateTimeOffset)serverEvent.Start.Value.ToLocalTime();
            EndDate = (DateTimeOffset)serverEvent.End.Value.ToLocalTime();

            // Remove HTML tags if the body is returned as HTML.
            string bodyType = serverEvent.Body.ContentType.ToString();
            if (bodyType == "HTML")
            {
                bodyContent = Regex.Replace(bodyContent, "<[^>]*>", "");
                bodyContent = Regex.Replace(bodyContent, "\n", "");
                bodyContent = Regex.Replace(bodyContent, "\r", "");
            }
            Body = bodyContent;
            Attendees = _calenderOperations.BuildAttendeeList(serverEvent.Attendees);
        }
コード例 #19
0
 public PaymentEntity(IEvent thisEvent, IMember member, int paymentId = 0)
 {
     this.PaymentId = paymentId;
     this.Event = thisEvent;
     this.Member = member;
     this.Date = DateTime.Now;
 }
コード例 #20
0
    public bool HandleEvent(IEvent @event)
    {
        var sceneChangeEvent = @event as SceneChangeEvent;
        if (sceneChangeEvent == null)
        {
            return true;
        }

        var data = @event.GetData() as string;
        if (data == null)
        {
            return true;
        }

        try
        {
            this.currentScene = (SceneNames)Enum.Parse(typeof(SceneNames), data, ignoreCase: true);
        }
        catch
        {
            // do nothing
        }

        return true;
    }
コード例 #21
0
        /// <summary>
        /// Tries to parse the given data to the target <see cref="IEvent"/>.
        /// </summary>
        /// <param name="eventParams">List of string-parameters to parse.</param>
        /// <param name="target">Target instance to parse the data to.</param>
        /// <returns><c>true</c> if the parsing was succesful, otherwise <c>false</c> is returned.</returns>
        public bool TryParse(List<string> eventParams, IEvent target)
        {
            if (eventParams.Count < 2)
            {
                return false;
            }

            if (string.IsNullOrEmpty(eventParams[0]))
            {
                return false;
            }

            float duration;
            if (!float.TryParse(eventParams[1], out duration))
            {
                return false;
            }

            if(!target.HasProperty("Name") || !target.HasProperty("Duration"))
            {
                return false;
            }

            target.SetProperty("Name", eventParams[0]);
            target.SetProperty("Duration", duration);
            return true;
        }
コード例 #22
0
        /// <summary>
        /// Deconstructs the contexts request into a set of prameters for the context.
        /// </summary>
        /// <remarks>
        /// The deafult implementation uses the convention of `/area/concern/action.aspc/tail?querystring`
        /// </remarks>
        /// <param name="ev">The vent that was considered for this action.</param>
        /// <param name="context">The context to act upon.</param>
        public override void Action(IEvent ev, IWebContext context)
        {
            // eliminate the app directory from the path
            string path = _appDirectory.Length > 0 ? context.Request.UrlInfo.AppPath.Trim('/').Replace(_appDirectory, "") : context.Request.UrlInfo.AppPath;
            path = path.Trim('/');

            if (!String.IsNullOrEmpty(context.Request.UrlInfo.File)) {
                context.Params["action"] = context.Request.UrlInfo.File.Split('.')[0].ToLower();

                string[] parts = path.Split('/');
                if (parts.Length >= 2) {
                    context.Params["area"] = parts[parts.Length - 2].ToLower();
                    context.Params["concern"] = parts[parts.Length - 1].ToLower();
                } else if (parts.Length == 1) {
                    context.Params["area"] = parts[0];
                }
            }

            // import query string and form values
            context.Params.Import(context.Request.Params.Where(kv => !kv.Key.StartsWith("_")));
            // establish flags
            foreach (string flag in context.Request.Flags.Where(f => !f.StartsWith("_"))) {
                context.Flags.Add(flag);
            }
            context.Params.Import(context.Request.Headers);
            // note method and tail
            context.Params["method"] = context.Request.Method;
            context.Params["tail"] = context.Request.UrlInfo.Tail;
            string requestViews = String.Join(";", context.Request.UrlInfo.Tail.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries));
            if (!String.IsNullOrEmpty(requestViews)) {
                context.Params["views"] = requestViews;
            }
        }
コード例 #23
0
ファイル: IEventHelpers.cs プロジェクト: splitice/EventCore
 void IEventHelpers.RegisterSocketRead(IEvent e, BufferedSocket socket, IEventHandler protocol,
                                       ReadFunction callback)
 {
     //Contract.Requires(socket != null);
     Contract.Requires(protocol != null);
     Contract.Requires(callback != null);
 }
コード例 #24
0
 public void run(IEvent e)
 {
     BoardMovedNotify notify = new BoardMovedNotify();
     this.boardMachine.fireStateChangedNotification(notify);
     LOG.Info(NAME);
     this.boardMachine.consumeEvent(new BoardReadyEvent());
 }
コード例 #25
0
        public static bool CreateEvent(IEvent thisEvent)
        {
            if (Connect())
            {
                try
                {
                    SqlCommand Command = Connection.CreateCommand();
                    Command.CommandType = CommandType.StoredProcedure;
                    Command.CommandText = "fif_event_create";

                    Command.Parameters.AddWithValue("name", thisEvent.Name);
                    Command.Parameters.AddWithValue("price", thisEvent.Price);
                    Command.Parameters.AddWithValue("description", thisEvent.Description);
                    Command.Parameters.AddWithValue("start_period", thisEvent.StartPeriod);
                    Command.Parameters.AddWithValue("end_period", thisEvent.EndPeriod);
                    Command.Parameters.AddWithValue("max_number_of_participants", thisEvent.MaxNumberOfParticipants);

                    Command.Parameters.Add("@activity_id", SqlDbType.Int, 0, "activity_id");
                    Command.Parameters["@activity_id"].Direction = ParameterDirection.Output;

                    Command.ExecuteNonQuery();

                    thisEvent.ActivityId = int.Parse(Command.Parameters["@activity_id"].Value.ToString());

                    Disconnect();
                    return true;
                }
                catch
                {
                    Disconnect();
                    return false;
                }
            }
            return false;
        }
コード例 #26
0
ファイル: Utils.cs プロジェクト: KangChaofan/OOC
        /// <summary>
        /// Converts event to <c>string</c> representation.
        /// </summary>
        /// <param name="Event">Event to be converted to <c>string</c></param>
        /// <returns>Returns resulting <c>string</c>.</returns>
        public static string EventToString( IEvent Event )
        {
            StringBuilder builder = new StringBuilder( 200 );
            builder.Append( "[Type=" );
            builder.Append( Event.Type.ToString() );

            if( Event.Description!=null )
            {
                builder.Append( "][Message=" );
                builder.Append( Event.Description );
            }

            if( Event.Sender != null )
            {
                builder.Append( "][ModelID=" );
                builder.Append( ((ILinkableComponent) Event.Sender).ModelID );
            }

            if( Event.SimulationTime != null )
            {
                builder.Append( "][SimTime=" );
                builder.Append( CalendarConverter.ModifiedJulian2Gregorian(Event.SimulationTime.ModifiedJulianDay).ToString() );
            }

            builder.Append( ']' );

            return( builder.ToString() );
        }
コード例 #27
0
ファイル: Event.cs プロジェクト: iraychen/LCLFramework
        private void LoadIEvent()
        {
            if (_ievent == null)
            {
                if (this.ScheduleType == null)
                {
                    Logger.LogInfo("计划任务没有定义其 type 属性");
                    
                }

                Type type = Type.GetType(this.ScheduleType);
                if (type == null)
                {
                    Logger.LogInfo(string.Format("计划任务 {0} 无法被正确识别", this.ScheduleType));
                }
                else
                {
                    _ievent = (IEvent)Activator.CreateInstance(type);
                    if (_ievent == null)
                    {
                        Logger.LogInfo(string.Format("计划任务 {0} 未能正确加载", this.ScheduleType));
                    }
                }
            }
        }
コード例 #28
0
ファイル: EventMessage.cs プロジェクト: deveel/deveeldb
        public EventMessage(IEvent source)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            sourceMeta = new Dictionary<string, object>();
            eventMeta = new Dictionary<string, object>();

            var eventSource = source.EventSource;
            while (eventSource != null) {
                foreach (var meta in source.EventSource.Metadata) {
                    sourceMeta[meta.Key] = meta.Value;
                }

                eventSource = eventSource.ParentSource;
            }

            if (source.EventData != null) {
                foreach (var pair in source.EventData) {
                    eventMeta[pair.Key] = pair.Value;
                }
            }

            TimeStamp = source.TimeStamp;
        }
コード例 #29
0
 /// <summary>
 /// Listen for VirtualBox events.
 /// </summary>
 /// <param name="aEvent">VirtualBox event</param>
 void IEventListener.HandleEvent(IEvent aEvent)
 {
     if (aEvent.Type == VBoxEventType.VBoxEventType_OnMachineStateChanged)
     {
         vboxServer.UpdateServersState();
     }
 }
コード例 #30
0
 protected override IValidationResultCollection ValidateEvent(IEvent evt)
 {
     return ValidationResult.GetCompositeResults(
         ResourceManager,
         new PropertyCountValidation(ResourceManager, evt, "VEVENT", "LAST-MODIFIED")
     );
 }
コード例 #31
0
 public override void OnEvent(IEvent e)
 {
 }
コード例 #32
0
ファイル: EventStore.cs プロジェクト: ddd-cqrs-es/CQRSExample
 public EventInfo(Guid id, IEvent eventData, int version)
 {
     EventData = eventData;
     Id        = id;
     Version   = version;
 }
コード例 #33
0
 public void Publish(IEvent @event)
 {
     throw new NotImplementedException();
 }
コード例 #34
0
 public void AddEvent(IEvent @event)
 {
     Console.WriteLine(@event.GetEventType());
 }
コード例 #35
0
 protected void ApplyChanges(IEvent evt)
 {
     this.Apply(evt);
     this.changes.Add(evt);
 }
コード例 #36
0
 public string Serialize(IEvent theEvent)
 {
     return(JsonConvert.SerializeObject(theEvent, typeof(IEvent), _serializerSettings));
 }
コード例 #37
0
ファイル: HolyShield.cs プロジェクト: drawde/BattleForAzeroth
 public bool TryCapture(Card card, IEvent @event) => false;
コード例 #38
0
 public EventController(IEvent repository, IConfiguration configuration)
 {
     this.repository = repository;
     Configuration   = configuration;
 }
コード例 #39
0
ファイル: Notice.cs プロジェクト: zarakay/Bugsnag.NET
 public Notice(string apiKey, INotifier notifier, IEvent evt)
     : this(apiKey, notifier, new IEvent[] { evt })
 {
 }
コード例 #40
0
 protected internal virtual void Apply(IEvent e)
 {
     OnApplying(e);
     _state.Mutate(e);
     _changes.Add(e);
 }
コード例 #41
0
        private void appendEvent(NpgsqlCommand conn, EventMapping eventMapping, Guid stream, IEvent @event)
        {
            if (@event.Id == Guid.Empty)
            {
                @event.Id = Guid.NewGuid();
            }

            conn.CallsSproc("mt_append_event")
            .With("stream", stream)
            .With("stream_type", eventMapping.Stream.StreamTypeName)
            .With("event_id", @event.Id)
            .With("event_type", eventMapping.EventTypeName)
            .With("body", _serializer.ToJson(@event), NpgsqlDbType.Jsonb)
            .ExecuteNonQuery();
        }
コード例 #42
0
 void IAttributeSetState.Mutate(IEvent e)
 {
     throw new NotSupportedException();
 }
コード例 #43
0
        public static byte[] ToMessage(this IEvent @event)
        {
            var json = JsonConvert.SerializeObject(@event);

            return(Encoding.UTF8.GetBytes(json));
        }
コード例 #44
0
 public void When(IEvent @event)
 {
     ((dynamic)this._handler).Handle((dynamic)@event);
 }
コード例 #45
0
ファイル: RxSpyStreamWriter.cs プロジェクト: weldingham/RxSpy
 void EnqueueEvent(IEvent ev)
 {
     _queue.Enqueue(ev);
 }
コード例 #46
0
 public T ApplyProjection <T>(string projectionName, T aggregate, IEvent @event) where T : IAggregate
 {
     throw new NotImplementedException();
 }
コード例 #47
0
ファイル: BasicScope.cs プロジェクト: tawmuller/fluorinefx
 /// <summary>
 /// Handle an event.
 /// </summary>
 /// <param name="event">Event to handle.</param>
 /// <returns>true if event was handled, false if it should bubble.</returns>
 public bool HandleEvent(IEvent @event)
 {
     return(false);
 }
コード例 #48
0
ファイル: EventBus.cs プロジェクト: IAmSilK/openmod
        public virtual async Task EmitAsync(IOpenModComponent component, object sender, IEvent @event,
                                            EventExecutedCallback callback = null)
        {
            if (!component.IsComponentAlive)
            {
                return;
            }

            var currentType = @event.GetType();

            while (currentType != null && typeof(IEvent).IsAssignableFrom(currentType))
            {
                string eventName = GetEventName(currentType);

                m_Logger.LogTrace($"Emitting event: {eventName}");
                var eventSubscriptions
                    = m_EventSubscriptions
                      .Where(c => (c.EventType != null && c.EventType == currentType) ||
                             (eventName.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) &&
                              c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive))
                      .ToList();


                void Complete()
                {
                    m_Logger.LogTrace($"{eventName}: Finished.");
                }

                if (eventSubscriptions.Count == 0)
                {
                    m_Logger?.LogTrace($"{eventName}: No listeners found.");
                    continue;
                }

                var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst);
                eventSubscriptions.Sort((a, b) =>
                                        comparer.Compare(
                                            (Priority)a.EventListenerAttribute.Priority,
                                            (Priority)b.EventListenerAttribute.Priority)
                                        );

                foreach (var group in eventSubscriptions.GroupBy(e => e.Scope))
                {
                    await using var newScope = group.Key.BeginLifetimeScope("AutofacWebRequest");
                    foreach (var subscription in group)
                    {
                        var cancellableEvent = @event as ICancellableEvent;

                        if (cancellableEvent != null &&
                            cancellableEvent.IsCancelled &&
                            !subscription.EventListenerAttribute.IgnoreCancelled)
                        {
                            continue;
                        }

                        var wasCancelled = false;
                        if (cancellableEvent != null)
                        {
                            wasCancelled = cancellableEvent.IsCancelled;
                        }

                        var serviceProvider = newScope.Resolve <IServiceProvider>();

                        try
                        {
                            await subscription.Callback.Invoke(serviceProvider, sender, @event);

                            if (cancellableEvent != null && subscription.EventListenerAttribute.Priority ==
                                EventListenerPriority.Monitor)
                            {
                                if (cancellableEvent.IsCancelled != wasCancelled)
                                {
                                    cancellableEvent.IsCancelled = wasCancelled;
                                    m_Logger.LogWarning(
                                        $"{((IOpenModComponent)@subscription.Owner.Target).OpenModComponentId} changed {@eventName} cancellation status with Monitor priority which is not permitted.");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            m_Logger.LogError(ex, $"Exception occured during event {@eventName}");
                        }
                    }

                    currentType = currentType.BaseType;
                }

                Complete();
            }

            callback?.Invoke(@event);
        }
コード例 #49
0
 public GameState When(IEvent @event) => this;
コード例 #50
0
ファイル: BasicScope.cs プロジェクト: tawmuller/fluorinefx
 /// <summary>
 /// Notifies the event.
 /// </summary>
 /// <param name="event">The event.</param>
 public void NotifyEvent(IEvent @event)
 {
 }
コード例 #51
0
ファイル: AzureEventBusReceiver.cs プロジェクト: eaba/CQRS
        protected virtual void ReceiveEvent(BrokeredMessage message)
        {
            DateTimeOffset startedAt     = DateTimeOffset.UtcNow;
            Stopwatch      mainStopWatch = Stopwatch.StartNew();
            string         responseCode  = "200";
            // Null means it was skipped
            bool?              wasSuccessfull      = true;
            string             telemetryName       = string.Format("Cqrs/Handle/Event/{0}", message.MessageId);
            ISingleSignOnToken authenticationToken = null;

            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/Servicebus" }
            };
            object value;

            if (message.Properties.TryGetValue("Type", out value))
            {
                telemetryProperties.Add("MessageType", value.ToString());
            }
            TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles++, telemetryProperties);
            var brokeredMessageRenewCancellationTokenSource = new CancellationTokenSource();

            try
            {
                Logger.LogDebug(string.Format("An event message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBody <string>();

                IEvent <TAuthenticationToken> @event = AzureBusHelper.ReceiveEvent(messageBody, ReceiveEvent,
                                                                                   string.Format("id '{0}'", message.MessageId),
                                                                                   () =>
                {
                    wasSuccessfull = null;
                    telemetryName  = string.Format("Cqrs/Handle/Event/Skipped/{0}", message.MessageId);
                    responseCode   = "204";
                    // Remove message from queue
                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException exception)
                    {
                        throw new MessageLockLostException(string.Format("The lock supplied for the skipped event message '{0}' is invalid.", message.MessageId), exception);
                    }
                    Logger.LogDebug(string.Format("An event message arrived with the id '{0}' but processing was skipped due to event settings.", message.MessageId));
                    TelemetryHelper.TrackEvent("Cqrs/Handle/Event/Skipped", telemetryProperties);
                },
                                                                                   () =>
                {
                    AzureBusHelper.RefreshLock(brokeredMessageRenewCancellationTokenSource, message, "event");
                }
                                                                                   );

                if (wasSuccessfull != null)
                {
                    if (@event != null)
                    {
                        telemetryName       = string.Format("{0}/{1}", @event.GetType().FullName, @event.Id);
                        authenticationToken = @event.AuthenticationToken as ISingleSignOnToken;

                        var telemeteredMessage = @event as ITelemeteredMessage;
                        if (telemeteredMessage != null)
                        {
                            telemetryName = telemeteredMessage.TelemetryName;
                        }

                        telemetryName = string.Format("Cqrs/Handle/Event/{0}", telemetryName);
                    }
                    // Remove message from queue
                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException exception)
                    {
                        throw new MessageLockLostException(string.Format("The lock supplied for event '{0}' of type {1} is invalid.", @event.Id, @event.GetType().Name), exception);
                    }
                }
                Logger.LogDebug(string.Format("An event message arrived and was processed with the id '{0}'.", message.MessageId));

                IList <IEvent <TAuthenticationToken> > events;
                if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                {
                    events.Add(@event);
                }
            }
            catch (MessageLockLostException exception)
            {
                IDictionary <string, string> subTelemetryProperties = new Dictionary <string, string>(telemetryProperties);
                subTelemetryProperties.Add("TimeTaken", mainStopWatch.Elapsed.ToString());
                TelemetryHelper.TrackException(exception, null, subTelemetryProperties);
                if (ThrowExceptionOnReceiverMessageLockLostExceptionDuringComplete)
                {
                    Logger.LogError(exception.Message, exception: exception);
                    // Indicates a problem, unlock message in queue
                    message.Abandon();
                    wasSuccessfull = false;
                }
                else
                {
                    Logger.LogWarning(exception.Message, exception: exception);
                    try
                    {
                        message.DeadLetter("LockLostButHandled", "The message was handled but the lock was lost.");
                    }
                    catch (Exception)
                    {
                        // Oh well, move on.
                        message.Abandon();
                    }
                }
                responseCode = "599";
            }
            catch (Exception exception)
            {
                TelemetryHelper.TrackException(exception, null, telemetryProperties);
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("An event message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
                message.Abandon();
                wasSuccessfull = false;
                responseCode   = "500";
                telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                telemetryProperties.Add("ExceptionMessage", exception.Message);
            }
            finally
            {
                // Cancel the lock of renewing the task
                brokeredMessageRenewCancellationTokenSource.Cancel();
                TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles--, telemetryProperties);

                mainStopWatch.Stop();
                TelemetryHelper.TrackRequest
                (
                    telemetryName,
                    authenticationToken,
                    startedAt,
                    mainStopWatch.Elapsed,
                    responseCode,
                    wasSuccessfull == null || wasSuccessfull.Value,
                    telemetryProperties
                );

                TelemetryHelper.Flush();
            }
        }
コード例 #52
0
 private IEvent RaiseEvent(IEvent @event, Action whenEvent)
 {
     whenEvent();
     return(@event);
 }
コード例 #53
0
 public bool HandlesEvent(IEvent Event)
 {
     return(true);
 }
コード例 #54
0
ファイル: AzureEventBusReceiver.cs プロジェクト: eaba/CQRS
 public virtual bool?ReceiveEvent(IEvent <TAuthenticationToken> @event)
 {
     return(AzureBusHelper.DefaultReceiveEvent(@event, Routes, "Azure-ServiceBus"));
 }
コード例 #55
0
 private Order GetOrder(IEvent evt)
 {
     return(_ctx.Orders.Single(p => p.Id == evt.AggregateId));
 }
コード例 #56
0
 public void Save(IEvent @event)
 => _events.Add(@event);
コード例 #57
0
 public abstract Task SaveEventAsync(IEvent @event);
コード例 #58
0
 public void OnEvent(IEvent theEvent)
 {
     throw new System.Exception("Not implemented for testing");
 }
コード例 #59
0
 protected void RaiseEvent(IEvent @event)
 {
     RaiseEvent(Envelope.Create(@event));
 }
コード例 #60
0
ファイル: Event.cs プロジェクト: zkitX/LeaguePackets
 public static void WriteEvent(this ByteWriter writer, IEvent ev)
 {
     writer.WriteByte((byte)ev.ID);
     ev.WriteArgs(writer);
 }