public void OnError(Exception exception, IEventMessage @event, IEventListener eventListener)
        {
            var eventListenerType = eventListener is IEventListenerProxy ? ((IEventListenerProxy)eventListener).TargetType : eventListener.GetType();

            _logger.LogError($"EventListener [{eventListenerType.Name}] failed to handle event [{@event.Identifier}] ({@event.PayloadType}). " +
                             "Continuing processing with next listener", exception);
        }
 public static IEnumerable <IEventMessage <DomainAggregateEvent> > Upgrade <TSource>(
     this IEventMessage <TSource> oldMessage, params DomainAggregateEvent[] newEvents)
     where TSource : DomainAggregateEvent
 {
     return(newEvents.Select(newEvent =>
                             (IEventMessage <DomainAggregateEvent>)UpgradedEventMessage.Create(oldMessage, newEvent)));
 }
        public void SendAndReceiveWithTopicsCorrectly()
        {
            //Arrange
            IEventMessage  receivedMessage = null;
            AutoResetEvent flag            = new AutoResetEvent(false);

            var sender   = _context.CreateMessageSender();
            var receiver = _context.CreateMessageReceiver("TestQueue", new List <string>()
            {
                "test"
            });

            receiver.DeclareQueue();

            var message = new EventMessage("test", "TestMessage");

            //Act
            sender.SendMessage(message);

            receiver.StartReceivingMessages(eventMessage =>
            {
                receivedMessage = eventMessage;
                flag.Set();
            });

            flag.WaitOne();

            //Assert
            Assert.IsNotNull(receivedMessage);
            Assert.AreEqual("TestMessage", receivedMessage.Message);
        }
Exemplo n.º 4
0
        protected override string OnInitState(IEventMessage message)
        {
            var eventMessage = TypeCast(message);
            if (eventMessage == null) return StateType.INIT;

            var agentSession = new AgentSession(eventMessage.Handler)
            {
                ConferenceId = eventMessage.ConferenceId,
                AgentName = eventMessage.AgentName,
                PublisherUrl = eventMessage.PresentationUrl,
                EndpointAddress = eventMessage.EndpointAddress,
                IsPublisher = true
            };

            sessionContext.Register(agentSession);

            agentSession.Process(new ResponseEvent
            {
                AgentName = sessionContext.SessionOfAgent.AgentName,
                ConferenceId = sessionContext.SessionOfAgent.ConferenceId,
                PresentationUrl = eventMessage.PresentationUrl,
                SessionId = sessionContext.SessionId,
                ResponseStatus = ResponseStatus.Ok
            });

            return StateType.READY;
        }
 public Review OnReview(
     Episode episode,
     IEventMessage message,
     [Service] IReviewRepository _repository)
 {
     return((Review)message.Payload);
 }
Exemplo n.º 6
0
        public void Send(IEventMessage message)
        {
            var eventBuilder = EventBuilder.Build(message);
            var data         = eventBuilder.ToByteArray();

            this.Client.Send(data, data.Length);
        }
Exemplo n.º 7
0
        /// <summary>
        /// RunTask
        /// </summary>
        /// <param name="transfer"></param>
        private void RunTask(IEventMessage transfer)
        {
            String eventMessage = transfer.EventMessage;                               //事件消息

            KeyValuePair<string, string> taskEventPair = new KeyValuePair<string, string>(Status, eventMessage);//事件-传输子对

            //判断是否存在任务,如果不存在任务的话,保持现状
            if (_tTaskTable.ContainsKey(taskEventPair))
            {
                //根据事件-传输子对取得一个任务
                StateMachineTask stateMachineTask = _tTaskTable[taskEventPair];
                //判断任务是否存在
                if (stateMachineTask != null)
                {
                    //判断任务中是否有下一个状态
                    if (stateMachineTask.NextStatus != null)
                    {
                        //设定下一个状态
                        Status = stateMachineTask.NextStatus;
                    }
                    //判断动作是否存在
                    if (stateMachineTask.Action != null)
                    {
                        //载入传输子,执行动作
                        stateMachineTask.Action(transfer);
                    }
                }
            }
        }
Exemplo n.º 8
0
        public void Publish(IEventMessage <object> msg, TParent declaringInstance)
        {
            var targetList = _eventTargetResolver(msg, declaringInstance);

            targetList.GetRange(0, targetList.Count) // Creates copy to prevent ConcurrentModificationException.
            .ForEach(target => _entityModel.Publish(msg, target));
        }
Exemplo n.º 9
0
        public async Task SetCheckpointAsync(IEventMessage eventArgs, IEnumerable <KeyValuePair <Metric, double> > metrics = null)
        {
            EnsureArg.IsNotNull(eventArgs);
            EnsureArg.IsNotNullOrWhiteSpace(eventArgs.PartitionId);

            try
            {
                var partitionId = eventArgs.PartitionId;
                var checkpoint  = new Checkpoint
                {
                    LastProcessed = eventArgs.EnqueuedTime,
                    Id            = partitionId,
                    Prefix        = _blobPath,
                };

                await UpdateCheckpointAsync(checkpoint);

                _logger.LogMetric(EventMetrics.EventWatermark(partitionId), 1);

                if (metrics != null)
                {
                    foreach (var metric in metrics)
                    {
                        _logger.LogMetric(metric.Key, metric.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(new StorageCheckpointClientException($"Unable to set checkpoint. {ex.Message}", ex));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 实时广播事件
        /// </summary>
        public void SendMessage(int eventId, IEventMessage message)
        {
            if (_listeners.ContainsKey(eventId) == false)
            {
                return;
            }

            LinkedList <Action <IEventMessage> > listeners = _listeners[eventId];

            if (listeners.Count > 0)
            {
                var currentNode = listeners.Last;
                while (currentNode != null)
                {
                    currentNode.Value.Invoke(message);
                    currentNode = currentNode.Previous;
                }
            }

            // 回收引用对象
            IReference refClass = message as IReference;

            if (refClass != null)
            {
                ReferencePool.Release(refClass);
            }
        }
 protected void TestEventMessageProperties <T>(AssertHelper assertHelper, IEventMessage <T> message, long timestamp, int productId, string eventId, long?requestId) where T : class, ISportEvent
 {
     TestMessageProperties(assertHelper, message, timestamp, productId);
     assertHelper.IsNotNull(() => message.Event);
     assertHelper.AreEqual(() => message.Event.Id.ToString(), eventId);
     assertHelper.AreEqual(() => message.RequestId, requestId);
 }
Exemplo n.º 12
0
    /// <summary>
    /// 事件处理
    /// </summary>
    private void OnHandleEventMessage(IEventMessage msg)
    {
        if (msg is PatchEventMessageDefine.PatchStatesChange)
        {
            var message = msg as PatchEventMessageDefine.PatchStatesChange;

            // 初始化结束
            if (message.CurrentStates == EPatchStates.InitiationOver)
            {
                PatchWindow.Instance.Initialize();
            }

            // 补丁下载完毕
            // 注意:在补丁下载结束之后,一定要强制释放资源管理器里所有的资源,还有重新载入Unity清单。
            if (message.CurrentStates == EPatchStates.DownloadOver)
            {
                PatchWindow.Instance.Destroy();
                ResourceManager.Instance.ForceReleaseAll();
                PatchManager.Instance.ReloadUnityManifest();

                // 开始游戏
                StartGame();
            }
        }
        else if (msg is PatchEventMessageDefine.OperationEvent)
        {
            PatchManager.Instance.HandleEventMessage(msg);
        }
    }
Exemplo n.º 13
0
 private bool SubmitMessage(IEventMessage message)
 {
     try
     {
         if (_messageQueue.TryAdd(message))
         {
             _inputCapacityExceeded.GetAndSet(false);
         }
         else
         {
             // This doesn't mean that the output event buffer is full, but rather that the main thread is
             // seriously backed up with not-yet-processed events. We shouldn't see this.
             if (!_inputCapacityExceeded.GetAndSet(true))
             {
                 Log.Warn("Events are being produced faster than they can be processed");
             }
         }
     }
     catch (InvalidOperationException)
     {
         // queue has been shut down
         return(false);
     }
     return(true);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Write an event message to Microsoft SQL Server.
        /// </summary>
        /// <param name="message">EventMessage</param>
        public virtual void Write(IEventMessage message)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = _connection;
#pragma warning disable CA2100 // Cannot use parameter for table name. Tablename is already checked in the CreateTable method.
                command.CommandText = "INSERT INTO [" + _tableName + "]([EventType],[TimeStamp],[Source],[Content],[Application]) VALUES (@EventType,@TimeStamp,@Source,@Content,@Application)";
#pragma warning disable CA2100 // Cannot use parameter for table name. Tablename is already checked in the CreateTable method.
                command.Parameters.Add("EventType", SqlDbType.SmallInt).Value = (short)message.Level;
                //command.Parameters.Add("Host", SqlDbType.VarChar, 255).Value = message.Host;
                command.Parameters.Add("TimeStamp", SqlDbType.DateTime).Value       = message.TimeStamp;
                command.Parameters.Add("Source", SqlDbType.VarChar, 255).Value      = message.Source;
                command.Parameters.Add("Content", SqlDbType.VarChar).Value          = message.Content;
                command.Parameters.Add("Application", SqlDbType.VarChar, 255).Value = _application;
                if (command.ExecuteNonQuery() != 1)
                {
                    throw new Exception("BlackBox.Write : Error writing to black box database table");
                }
            }
            if (!_keepConnectionOpen)
            {
                _connection.Close();
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Write an event message to Microsoft SQL Server.
        /// </summary>
        /// <param name="message">EventMessage</param>
        public virtual void Write(IEventMessage message)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
            using (IDbCommand command = _connection.CreateCommand())
            {
                command.Connection = _connection;
#pragma warning disable CA2100 // Cannot use parameter for table name. Tablename is already checked in the CreateTable method.
                command.CommandText = "INSERT INTO [" + _tableName + "]([EventType],[TimeStamp],[Source],[Content],[Application]) VALUES (@EventType,@TimeStamp,@Source,@Content,@Application)";
#pragma warning disable CA2100 // Cannot use parameter for table name. Tablename is already checked in the CreateTable method.
                command.AddParameter("EventType", (short)message.Level);
                command.AddParameter("TimeStamp", message.TimeStamp);
                command.AddParameter("Source", message.Source, 255);
                command.AddParameter("Content", message.Content);
                command.AddParameter("Application", _application, 255);
                if (command.ExecuteNonQuery() != 1)
                {
                    throw new Exception("BlackBox.Write : Error writing to black box data store table");
                }
            }
            if (!_keepConnectionOpen)
            {
                _connection.Close();
            }
        }
Exemplo n.º 16
0
        public Task SubscribeTwoConsumer_SendOneMessage_BothConsumerReceivesMessage()
        {
            return(TryTest(async() =>
            {
                // arrange
                var cts = new CancellationTokenSource(30000);
                var eventDescription = new EventDescription(
                    Guid.NewGuid().ToString());

                // act
                IEventStream consumerOne = await _registry
                                           .SubscribeAsync(eventDescription);
                IEventStream consumerTwo = await _registry
                                           .SubscribeAsync(eventDescription);
                var outgoing = new EventMessage(eventDescription, "bar");
                await _sender.SendAsync(outgoing);

                // assert
                IEventMessage incomingOne =
                    await consumerOne.ReadAsync(cts.Token);
                IEventMessage incomingTwo =
                    await consumerTwo.ReadAsync(cts.Token);
                Assert.Equal(outgoing.Payload, incomingOne.Payload);
                Assert.Equal(outgoing.Payload, incomingTwo.Payload);
            }));
        }
        private void WriteMessageData(IOddsFeedSession session, IEventMessage <ISportEvent> message, DateTime messageUserReceived = default, double processingTotalMilliSeconds = 0)
        {
            var userStartProcessing = DateTime.Now;
            var sdkProcessingTime   = (userStartProcessing - Helper.FromEpochTime(message.Timestamps.Received)).TotalMilliseconds;
            var createdToUserTime   = (userStartProcessing - Helper.FromEpochTime(message.Timestamps.Created)).TotalMilliseconds;
            var pureSdkTime         = messageUserReceived == default
                ? sdkProcessingTime
                : (userStartProcessing - messageUserReceived).TotalMilliseconds;

            var messageName = message.GetType().Name;

            messageName = messageName.Substring(0, messageName.IndexOf("`", StringComparison.InvariantCultureIgnoreCase));
            var requestId       = message.RequestId.HasValue ? $", RequestId={message.RequestId}" : string.Empty;
            var producerMessage = $"[{message.Producer.Id}-{message.Producer.Name}|{Helper.ToEpochTime(message.Producer.LastTimestampBeforeDisconnect)}={message.Producer.LastTimestampBeforeDisconnect}|{!message.Producer.IsProducerDown}]";
            var processingTotalMilliSecondsStr = processingTotalMilliSeconds > 0 ? $", COMPLETED in {processingTotalMilliSeconds}ms" : string.Empty;
            var msg = $"{session.Name}: {messageName}:Producer={producerMessage}, GeneratedAt={message.Timestamps.Created}={Helper.FromEpochTime(message.Timestamps.Created)}, PureSdkProcessingTime={(int)pureSdkTime}ms, SdkProcessingTime={(int)sdkProcessingTime}ms, Behind={(int)createdToUserTime}ms, EventId={message.Event.Id}{requestId}{processingTotalMilliSecondsStr}.";

            Helper.WriteToOutput(msg);
            _log.LogInformation(msg);

            if (message.Timestamps.Sent == 0)
            {
                msg = $"Message {messageName} created {message.Timestamps.Created} on producer {message.Producer.Id}-{message.Producer.Name} does not have sent timestamp.";
                Helper.WriteToOutput(msg);
                _log.LogError(msg);
            }
        }
Exemplo n.º 18
0
        protected override IEnumerable <object> ResolveEventTargets(IEventMessage message, object parentEntity, PropertyInfo field, IForwardingMode eventForwardingMode)
        {
            var fieldValue       = field.GetValue(parentEntity);
            var valuesCollection = field.GetType().GetProperty(nameof(IDictionary.Values))?.GetValue(fieldValue) as IEnumerable;

            return(valuesCollection == null?Enumerable.Empty <object>() : eventForwardingMode.FilterCandidates(message, valuesCollection.Cast <object>()));
        }
Exemplo n.º 19
0
 private void OnHandleEvent(IEventMessage msg)
 {
     if (msg is LoginEvent.ConnectServer)
     {
         FsmManager.Instance.Transition(nameof(NodeTown));
     }
 }
Exemplo n.º 20
0
 public bool Equals(IEventMessage other)
 {
     return(Id.Equals(other.Id) &&
            EventType == other.EventType &&
            Message == other.Message &&
            CreatedDate.Equals(other.CreatedDate));
 }
        public bool TryProcessMessage(IEventMessage message, IMessageParameters parameters, TPeerType peer)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (peer == null)
            {
                throw new ArgumentNullException(nameof(peer));
            }

            TPayloadType payload = message.Payload.Data as TPayloadType;

            //if it's the not the payload type this handler handles then we
            //indicate non-consumption
            if (payload == null)
            {
                return(false);
            }
            else
            {
                OnIncomingHandlableMessage(message, payload, parameters, peer);
            }

            //If an exception wasn't thrown we'll be indicating that the payload has been consumed.
            return(true);
        }
        public IEvent <TKey, TAggregate> ToEvent <TKey, TAggregate>(IEventMessage eventMessage) where TAggregate : IAggregate <TKey>
        {
            var @event = (IEvent <TKey, TAggregate>)Serializer.Deserialize(eventMessage.ProducerMessage.MessageBytes, eventMessage.ProducerMessage.MessageType);

            @event.Version = eventMessage.EventId.Version;
            return(@event);
        }
Exemplo n.º 23
0
        ///// <summary>
        ///// Checks if there is at least one writer which logs on given event level.
        ///// </summary>
        ///// <param name="level">Event level to check.</param>
        ///// <returns>True is there is at least one writer that writers at given level.</returns>
        //public virtual bool InEnabled(EventLevel level)
        //{
        //    if (level == EventLevel.Debug && !Debugger.IsAttached) return false;
        //    for (int i = 0; i < _writers.Count; i++)
        //    {
        //        if (_writers[i].Level < level) return false;
        //    }
        //    return true;
        //}

        /// <summary>
        /// Write event message. Use fallback event writer when primairy writer throws an exception. This write method blocks until the writer is finished.
        /// </summary>
        /// <param name="message">Event message to write</param>
        public virtual void Write(IEventMessage message)
        {
            if (message == null)
            {
                return;
            }
            if (message.Level == EventLevel.Debug && !Debugger.IsAttached)
            {
                return;
            }
            for (int i = 0; i < _writers.Count; i++)
            {
                if (_writers[i].Level < message.Level)
                {
                    continue;
                }
                try
                {
                    _writers[i].Write(message);
                }
                catch (Exception exception)
                {
                    if (_writerFallBack != null)
                    {
                        try
                        {
                            _writerFallBack.Write(message);
                            _writerFallBack.Write(exception.ToMessage());
                        }
                        catch { }
                    }
                }
            }
        }
Exemplo n.º 24
0
        public async Task SetCheckpointAsync(IEventMessage eventArgs)
        {
            EnsureArg.IsNotNull(eventArgs);
            EnsureArg.IsNotNullOrWhiteSpace(eventArgs.PartitionId);

            try
            {
                var partitionId = eventArgs.PartitionId;
                var checkpoint  = new Checkpoint();
                checkpoint.LastProcessed = eventArgs.EnqueuedTime;
                checkpoint.Id            = partitionId;
                checkpoint.Prefix        = _blobPath;

                _checkpoints[partitionId] = checkpoint;
                var count = _lastCheckpointTracker.AddOrUpdate(partitionId, 1, (key, value) => value + 1);

                if (count >= _lastCheckpointMaxCount)
                {
                    await PublishCheckpointAsync(partitionId);

                    _log.LogMetric(EventMetrics.EventWatermark(partitionId, eventArgs.EnqueuedTime.UtcDateTime), 1);
                    _lastCheckpointTracker[partitionId] = 0;
                }
            }
#pragma warning disable CA1031
            catch (Exception ex)
#pragma warning restore CA1031
            {
                _log.LogError(new Exception($"Unable to set checkpoint. {ex.Message}"));
            }
        }
Exemplo n.º 25
0
        public void StartReceivingMessages_InvokesCallbackWithCorrectEventMessage()
        {
            // Arrange
            var channelMock = new Mock <IModel>();
            AsyncEventingBasicConsumer basicConsumer = null;

            channelMock.Setup(c => c.BasicConsume("TestQueue",
                                                  true,
                                                  "",
                                                  false,
                                                  false,
                                                  null,
                                                  It.IsAny <AsyncEventingBasicConsumer>()))
            .Callback((string queue,
                       bool autoAck,
                       string consumerTag,
                       bool noLocal,
                       bool exclusive,
                       IDictionary <string, object> arguments,
                       IBasicConsumer consumer) =>
            {
                basicConsumer = consumer as AsyncEventingBasicConsumer;
            });

            var connectionMock = new Mock <IConnection>();

            connectionMock.Setup(c => c.CreateModel())
            .Returns(channelMock.Object);

            var context  = new RabbitMQBusContext(connectionMock.Object, "TestExchange");
            var receiver = new RabbitMQMessageReceiver(context, "TestQueue", new List <string> {
                "TestTopic2"
            });

            // Act
            bool          callbackWasInvoked = false;
            IEventMessage eventMessage       = null;

            receiver.StartReceivingMessages((e) =>
            {
                callbackWasInvoked = true;
                eventMessage       = e;
            });
            var properties = new BasicProperties
            {
                Type          = "Test type",
                Timestamp     = new AmqpTimestamp(1542183431),
                CorrelationId = "test id"
            };

            basicConsumer.HandleBasicDeliver("", 0, false, "", "routing.key", properties, Encoding.UTF8.GetBytes("test message")).Wait();

            // Assert
            Assert.IsTrue(callbackWasInvoked);
            Assert.AreEqual("routing.key", eventMessage.RoutingKey);
            Assert.AreEqual("test message", eventMessage.Message);
            Assert.AreEqual("Test type", eventMessage.EventType);
            Assert.AreEqual(1542183431, eventMessage.Timestamp);
            Assert.AreEqual("test id", eventMessage.CorrelationId);
        }
 public void Publish(IEventMessage message, object target)
 {
     if (target != null)
     {
         RuntimeModelOf(target).DoPublish(message, target);
     }
 }
        public GenericObject OnData(
            int sensorId,
            IEventMessage message,
            //[Service] IUploadDataRepository _repository
            [Service] ITimeSeriesRepository _repository
            )
        {
            var data = (CreatedDataValues)message.Payload;
            List <(int, string)> sensorNameIdPairs = _repository.GetSensorTablePair(new List <int>()
            {
                data.sensorId
            });
            var queryString = "";

            foreach (var sensorNameIdPair in sensorNameIdPairs)
            {
                queryString = queryString + TimeSeriesQueryBuilder.CreateTimeSeriesQueryString(
                    sensorNameIdPair.Item1,
                    sensorNameIdPair.Item2,
                    data.fromDate,
                    data.toDate
                    );
            }
            return(_repository.GetTimeSeries("", queryString).Result);
        }
Exemplo n.º 28
0
        /// <summary>
        /// RunTask
        /// </summary>
        /// <param name="transfer"></param>
        private void RunTask(IEventMessage transfer)
        {
            String eventMessage = transfer.EventMessage;                                                           //事件消息

            KeyValuePair <string, string> taskEventPair = new KeyValuePair <string, string>(Status, eventMessage); //事件-传输子对

            //判断是否存在任务,如果不存在任务的话,保持现状
            if (_tTaskTable.ContainsKey(taskEventPair))
            {
                //根据事件-传输子对取得一个任务
                StateMachineTask stateMachineTask = _tTaskTable[taskEventPair];
                //判断任务是否存在
                if (stateMachineTask != null)
                {
                    //判断任务中是否有下一个状态
                    if (stateMachineTask.NextStatus != null)
                    {
                        //设定下一个状态
                        Status = stateMachineTask.NextStatus;
                    }
                    //判断动作是否存在
                    if (stateMachineTask.Action != null)
                    {
                        //载入传输子,执行动作
                        stateMachineTask.Action(transfer);
                    }
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Write an event message to the console.
        /// </summary>
        /// <param name="message"></param>
        public virtual void Write(IEventMessage message)
        {
            ConsoleColor tempForegroundColor = Console.ForegroundColor;
            ConsoleColor tempBackgroudnColor = Console.BackgroundColor;

            Console.BackgroundColor = ConsoleColor.Black;
            switch (message.Level)
            {
            case EventLevel.Critical: Console.ForegroundColor = ConsoleColor.Magenta; break;

            case EventLevel.Debug: Console.ForegroundColor = ConsoleColor.DarkGreen; break;

            case EventLevel.Error: Console.ForegroundColor = ConsoleColor.Red; break;

            case EventLevel.Trace: Console.ForegroundColor = ConsoleColor.Gray; break;

            case EventLevel.Warning: Console.ForegroundColor = ConsoleColor.DarkMagenta; break;

            case EventLevel.Info: Console.ForegroundColor = ConsoleColor.Gray; break;

            default: Console.ForegroundColor = ConsoleColor.Gray; break;
            }
            Console.WriteLine(FormatMessage(message));
            Console.ForegroundColor = tempForegroundColor;
            Console.BackgroundColor = tempBackgroudnColor;
        }
Exemplo n.º 30
0
        public Task SubscribeTwoConsumer_SendTwoMessage_BothConsumerReceivesIndependentMessage()
        {
            return(TryTest(async() =>
            {
                // arrange
                var cts = new CancellationTokenSource(30000);
                string name = Guid.NewGuid().ToString();
                var eventDescriptionOne = new EventDescription(
                    name, new ArgumentNode("b", "x"));
                var eventDescriptionTwo = new EventDescription(
                    name, new ArgumentNode("b", "y"));

                // act
                IEventStream consumerOne = await _registry
                                           .SubscribeAsync(eventDescriptionOne);
                var outgoingOne = new EventMessage(eventDescriptionOne, "foo");
                await _sender.SendAsync(outgoingOne);

                IEventStream consumerTwo = await _registry
                                           .SubscribeAsync(eventDescriptionTwo);
                var outgoingTwo = new EventMessage(eventDescriptionTwo, "bar");
                await _sender.SendAsync(outgoingTwo);

                // assert
                IEventMessage incomingOne =
                    await consumerOne.ReadAsync(cts.Token);
                IEventMessage incomingTwo =
                    await consumerTwo.ReadAsync(cts.Token);
                Assert.Equal(outgoingOne.Payload, incomingOne.Payload);
                Assert.Equal(outgoingTwo.Payload, incomingTwo.Payload);
                Assert.NotEqual(incomingOne.Event, incomingTwo.Event);
            }));
        }
    protected override void OnHandleEvent(IEventMessage msg)
    {
        if (msg is BattleEvent.DamageHurt)
        {
            if (CharData.IsDead == false)
            {
                BattleEvent.DamageHurt message = msg as BattleEvent.DamageHurt;
                CharData.DamageHurt(message.Damage);
                CharAnim.Play("getHit");

                // 随机播放角色受击音效
                string soundName = Avatar.GetRandomGetHitSound();
                if (string.IsNullOrEmpty(soundName) == false)
                {
                    AudioManager.Instance.PlaySound(soundName);
                }
            }
        }
        else if (msg is BattleEvent.CharacterDead)
        {
            CharSkill.ForbidAll();
            CharAnim.Play("die");

            // 播放角色死亡音效
            string soundName = Avatar.GetDeadSound();
            if (string.IsNullOrEmpty(soundName) == false)
            {
                AudioManager.Instance.PlaySound(soundName);
            }
        }
    }
        public string BuildMessage(IEvent @event)
        {
            IEventMessage builder = _builders[@event.EventType];
            string        message = builder == null ? "<UNKNOWN_EVENT_TYPE>" : builder.BuildMessage(@event);

            return(message);
        }
Exemplo n.º 33
0
        protected override string OnReadyState(IEventMessage message)
        {
            sessionContext.ResponseTimeoutContext.StopWatchObj.Stop();

            var eventMessage = TypeCast(message);
            if (eventMessage == null) return StateType.READY;

            var agentSession = sessionContext.GetPublisherSession(eventMessage.PresentationUrl);
            agentSession.Process(eventMessage);

            return StateType.READY;
        }
Exemplo n.º 34
0
        protected override string OnReadyState(IEventMessage message)
        {
            var eventMessage = TypeCast(message);
            if (eventMessage == null) return StateType.READY;

            var agentSession = sessionContext.GetPublisherSession(eventMessage.PresentationUrl);
            agentSession.Process(eventMessage);

            sessionContext.SessionOfAgent.Process(new ResponseEvent
                                                      {
                                                          AgentName = sessionContext.SessionOfAgent.AgentName,
                                                          ConferenceId = sessionContext.SessionOfAgent.ConferenceId,
                                                          PresentationUrl = eventMessage.PresentationUrl,
                                                          SessionId = sessionContext.SessionId,
                                                          ResponseStatus = ResponseStatus.Continue
                                                      });

            sessionContext.ResponseTimeoutContext.StopWatchObj.Start();

            return StateType.PLAYING;
        }
Exemplo n.º 35
0
 protected virtual string OnInitState(IEventMessage message)
 {
     return StateType.INIT;
 }
Exemplo n.º 36
0
 protected virtual string OnReadyState(IEventMessage message)
 {
     return StateType.READY;
 }
Exemplo n.º 37
0
 protected virtual string OnPlayingState(IEventMessage message)
 {
     return StateType.PLAYING;
 }
Exemplo n.º 38
0
 public Event(string name, IEventMessage message)
 {
     this.name = name;
     this.message = message;
 }
Exemplo n.º 39
0
            /// <summary>
            /// Deserialize the message
            /// </summary>
            /// <param name="map">An <see cref="OSDMap"/> containing the data</param>
            public void Deserialize(OSDMap map)
            {
                if (map.ContainsKey("ack"))
                    Messages = new EventQueueAck();
                else if (map.ContainsKey("events"))
                    Messages = new EventQueueEvent();
                else
                    Logger.Log("Unable to deserialize EventQueueGetMessage: No message handler exists for event", Helpers.LogLevel.Warning);

                Messages.Deserialize(map);
            }
Exemplo n.º 40
0
        public async Task Publish(IEventMessage message)
        {
            var topicClient = TopicClient.CreateFromConnectionString(_connectionString, message.GetType().FullName);

            await topicClient.SendAsync(BuildBrokeredMessage(message));
        }
Exemplo n.º 41
0
 private PlayEvent TypeCast(IEventMessage message)
 {
     return message is PlayEvent ? message as PlayEvent : null;
 }
Exemplo n.º 42
0
 protected override string OnInitState(IEventMessage message)
 {
     sessionContext.UnRegister();
     return StateType.END;
 }
Exemplo n.º 43
0
 protected override string OnReadyState(IEventMessage message)
 {
     return StateType.END;
 }
Exemplo n.º 44
0
 public void Send(IEventMessage message)
 {
     subscriber.Handle(message);
 }
Exemplo n.º 45
0
 private ResponseEvent TypeCast(IEventMessage message)
 {
     return message is ResponseEvent ? message as ResponseEvent : null;
 }
Exemplo n.º 46
0
        /// <summary>
        /// Interface method overload for receiving a <see cref="IEventMessage"/>.
        /// </summary>
        /// <param name="message">The event recieved from the remote peer.</param>
        /// <param name="parameters">The message parameters the message was sent with.</param>
        public void OnNetworkMessageReceive(IEventMessage message, IMessageParameters parameters)
        {
            Throw<ArgumentNullException>.If.IsNull(message)?.Now(nameof(message));

            EventPublisher?.Invoke(message, parameters);
        }
Exemplo n.º 47
0
 private AnnounceEvent TypeCast(IEventMessage message)
 {
     return message is AnnounceEvent ? message as AnnounceEvent : null;
 }
Exemplo n.º 48
0
 protected override string OnInitState(IEventMessage message)
 {
     throw new RuleException();
 }
Exemplo n.º 49
0
 public string Action(IEventMessage message, string currentState)
 {
     Func<IEventMessage, string> handler;
     return !actionPool.TryGetValue(currentState, out handler) ? currentState : handler(message);
 }
Exemplo n.º 50
0
 private TimeOutEvent TypeCast(IEventMessage message)
 {
     return message is TearDownEvent ? message as TimeOutEvent : null;
 }
Exemplo n.º 51
0
		public static void Send(IEventMessage eventMessage)
		{
			Instance.Send(eventMessage);
		}
Exemplo n.º 52
0
 /// <summary>
 /// 同步触发器
 /// </summary>
 /// <param name="transfer"></param>
 public void SyncTrigger(IEventMessage transfer)
 {
     //执行任务
     RunTask(transfer);
 }
Exemplo n.º 53
0
 public Task Publish(IEventMessage message)
 {
     return _sender.Publish(message);
 }
Exemplo n.º 54
0
 public Task Publish(IEventMessage message)
 {
     _messages.OnNext(message);
     return Task.FromResult(true);
 }