Пример #1
0
        /// <summary>
        /// Listens for incoming XML stanzas and raises the appropriate events.
        /// </summary>
        /// <remarks>This runs in the context of a separate thread. In case of an
        /// exception, the Error event is raised and the thread is shutdown.</remarks>
        private void ReadStream()
        {
            using (var reader = new StreamReader(_stream))
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    // If the client is not connected close reader.
                    if (!_client.Connected)
                    {
                        break;
                    }

                    var message = reader.ReadLineSingleBreak();
                    MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));

                    // Parse message
                    var command = CommandFactory.GetCommand(message);
                    if (command != null)
                    {
                        if (_resultTaskCompletionSources.TryGetValue(command.Code, out TaskCompletionSource <Command> resultTaskCompletionSource))
                        {
                            // query response
                            resultTaskCompletionSource.TrySetResult(command);
                        }
                        else
                        {
                            // event
                            EventReceived?.Invoke(this, new CommandEventArgs(command));
                        }
                    }
                }
            }
        }
Пример #2
0
 public EventReplier(int port, EventReceived eventReceived)
 {
     context = new ZContext();
     socket  = new ZSocket(context, ZSocketType.REP);
     socket.Bind($"tcp://127.0.0.1:{port}");
     onEventReceived = eventReceived;
 }
Пример #3
0
        public async Task Handle(EventReceived <CustomerCreated> @event, CancellationToken cancellationToken)
        {
            _logger.LogInformation("creating customer details for {AggregateId} ...", @event.Event.AggregateId);

            var filter = Builders <CustomerDetails> .Filter
                         .Eq(a => a.Id, @event.Event.AggregateId);

            var update = Builders <CustomerDetails> .Update
                         .Set(a => a.Id, @event.Event.AggregateId)
                         .Set(a => a.Version, @event.Event.AggregateVersion)
                         .Set(a => a.Firstname, @event.Event.Firstname)
                         .Set(a => a.Lastname, @event.Event.Lastname)
                         .Set(a => a.Email, @event.Event.Email)
                         .Set(a => a.TotalBalance, new Money(Currency.CanadianDollar, 0));

            await _db.CustomersDetails.UpdateOneAsync(filter,
                                                      cancellationToken : cancellationToken,
                                                      update : update,
                                                      options : new UpdateOptions()
            {
                IsUpsert = true
            });

            _logger.LogInformation("created customer details {AggregateId}", @event.Event.AggregateId);
        }
Пример #4
0
        public async Task Register(string eventName, EventReceived <TEvent> messageReceived)
        {
            await Task.Run(() =>
            {
                try
                {
                    _channel.ExchangeDeclare(eventName, ExchangeType.Fanout);

                    var queueName = _channel.QueueDeclare().QueueName;
                    _channel.QueueBind(queue: queueName,
                                       exchange: eventName,
                                       routingKey: "");

                    var consumer       = new EventingBasicConsumer(_channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = JsonConvert.DeserializeObject <TEvent>(Encoding.UTF8.GetString(body.ToArray()));
                        messageReceived(message);
                    };

                    _channel.BasicConsume(queue: eventName,
                                          autoAck: true,
                                          consumer: consumer);
                }
                catch (Exception e)
                {
                    throw new EventReceiverException(e);
                }
            });
        }
Пример #5
0
        public async Task Handle(EventReceived <Withdrawal> @event, CancellationToken cancellationToken)
        {
            var filter = Builders <AccountDetails> .Filter.Eq(a => a.Id, @event.Event.AggregateId);

            var account = await(await _db.AccountsDetails.FindAsync(filter, null, cancellationToken)).FirstOrDefaultAsync(cancellationToken);

            if (null == account)
            {
                _logger.LogWarning("unable to find account by id {AggregateId}", @event.Event.AggregateId);
                throw new ArgumentOutOfRangeException(nameof(@event.Event.AggregateId), $"unable to find account by id {@event.Event.AggregateId}");
            }

            var customerFilter = Builders <CustomerDetails> .Filter.Eq(a => a.Id, account.OwnerId);

            var update = Builders <CustomerDetails> .Update
                         .Inc(a => a.TotalBalance.Value, [email protected]);

            var res = await _db.CustomersDetails.FindOneAndUpdateAsync(customerFilter, update, null, cancellationToken);

            if (null == res)
            {
                var msg = $"unable to find customer by id {account.OwnerId}";
                _logger.LogWarning(msg);
                throw new ArgumentOutOfRangeException(nameof(account.OwnerId), msg);
            }
        }
Пример #6
0
        public async Task Handle(EventReceived <Withdrawal> @event, CancellationToken cancellationToken)
        {
            _logger.LogInformation("processing withdrawal of {@event.Event.Amount} on account {AggregateId} ...", @event.Event.AggregateId);

            var filter = Builders <AccountDetails> .Filter
                         .And(Builders <AccountDetails> .Filter.Eq(a => a.Id, @event.Event.AggregateId),
                              Builders <AccountDetails> .Filter.Eq(a => a.Version, @event.Event.AggregateVersion - 1));

            var update = Builders <AccountDetails> .Update
                         .Set(a => a.Version, @event.Event.AggregateVersion)
                         .Inc(a => a.Balance.Value, [email protected]);

            var res = await _db.AccountsDetails.FindOneAndUpdateAsync(
                filter : filter,
                cancellationToken : cancellationToken,
                update : update,
                options : new FindOneAndUpdateOptions <AccountDetails, AccountDetails>()
            {
                IsUpsert = false
            });

            if (res != null)
            {
                _logger.LogInformation("withdrawn {@event.Event.Amount} from account {AggregateId} ...", @event.Event.AggregateId);
            }
            else
            {
                _logger.LogWarning("withdrawal of {@event.Event.Amount} from account {AggregateId} failed!", @event.Event.AggregateId);
            }
        }
Пример #7
0
 public void RaiseClientEvent(EventCodes eventCode)
 {
     EventReceived?.Invoke(new EventData()
     {
         Code = (byte)eventCode
     });
 }
        public async Task Handle(EventReceived <AccountCreated> @event, CancellationToken cancellationToken)
        {
            _logger.LogInformation("creating account details for aggregate {AggregateId} ...", @event.Event.AggregateId);

            var customerId = @event.Event.OwnerId;
            var response   = await _customerDetailsContainer.ReadItemAsync <CustomerDetails>(
                customerId.ToString(),
                new PartitionKey(customerId.ToString()),
                null, cancellationToken);

            var customer = response.Resource;

            if (null == customer)
            {
                var msg = $"unable to find customer by id {@event.Event.OwnerId}";
                _logger.LogWarning(msg);
                throw new ArgumentOutOfRangeException(nameof(@event.Event.OwnerId), msg);
            }

            var balance    = Money.Zero(@event.Event.Currency);
            var newAccount = new AccountDetails(@event.Event.AggregateId,
                                                customer.Id, customer.Firstname, customer.Lastname,
                                                balance);
            await _accountsContainer.UpsertItemAsync(newAccount, new PartitionKey(@event.Event.AggregateId.ToString()),
                                                     null, cancellationToken);

            _logger.LogInformation("created account {AggregateId}", @event.Event.AggregateId);
        }
Пример #9
0
        private void ProcessEvent(JObject packet)
        {
            Type  requestType;
            var   name      = packet["event"].ToObject <string>();
            var   eventBody = packet["body"];
            Event eventObj;

            if (name != null &&
                _types != null &&
                _types.TryGetValue("event." + name, out requestType))
            {
                // We have a strongly typed event type registered, use that.
                eventObj = eventBody.ToObject(requestType) as Event;
            }
            else
            {
                // We have no strongly typed event type, so give the user a
                // GenericEvent and they can look through the body manually.
                eventObj = new GenericEvent()
                {
                    body = eventBody.ToObject <Dictionary <string, object> >()
                };
            }
            try {
                EventReceived?.Invoke(this, new EventReceivedEventArgs(name, eventObj));
            } catch (Exception) {
                // TODO: Report unhandled exception?
            }
        }
Пример #10
0
        private void ReceiveMessage(object sender, NetMQSocketEventArgs args)
        {
            NetMQMessage message = args.Socket.ReceiveMultipartMessage();

            if (message[message.FrameCount - 2].MessageSize != 0)
            {
                RaiseError("ProtocolError", "Invalid event: Second to last argument must be an empty buffer!");
                return;
            }

            var envelope = message.Take(message.FrameCount - 2).Select(n => n.ToByteArray()).ToList();

            Event evt;

            try
            {
                evt = SerializerUtils.Deserialize(envelope, message.Last.ToByteArray());
            }
            catch (Exception ex)
            {
                RaiseError("ProtocolError", $"Invalid event: {ex.Message}", ex.StackTrace);
                return;
            }

            if (evt.Header.ResponseTo != null && Channels.TryGetValue(evt.Header.ResponseTo, out Channel ch))
            {
                ch.ProcessAsync(evt);
            }
            else
            {
                EventReceived?.BeginInvoke(this, new EventReceivedArgs {
                    Event = evt
                }, null, null);
            }
        }
Пример #11
0
 protected void OnEventReceived(IpcEvent obj)
 {
     // Special case: progress report events are too noisy...
     if (!(obj.Data is ProgressReportEvent))
     {
         Logger.LogInfo("Event {0} of type \"{1}\" received from server.", obj.RequestId, obj.Data.GetType().Name);
     }
     EventReceived?.Invoke(obj);
 }
        public void SubscribeToEvent <TEvent>(EventReceived <TEvent> eventReceived) where TEvent : class, IEvent
        {
            if (eventReceived == null)
            {
                throw new ArgumentNullException(nameof(eventReceived));
            }

            _eventSubscriptions.Add(configurator => configurator.Handler <TEvent>(ctx => HandleEvent(eventReceived, ctx)));
        }
 public async Task Handle(EventReceived <AccountDeactivated> notification, CancellationToken cancellationToken)
 {
     // TODO: This is a test email
     await _sendGridService.SendEmailAsync(
         email : "*****@*****.**",
         subject : "ES CRM - Account deactivated",
         htmlMessage : notification.Event.Name
         );
 }
        public async Task Handle(EventReceived <AccountCreated> notification, CancellationToken cancellationToken)
        {
            NewAccountCreatedEmailTemplate newAccountCreatedEmailTemplate = new NewAccountCreatedEmailTemplate(notification.Event);

            // TODO: This is a test email
            await _sendGridService.SendEmailAsync(
                email : "*****@*****.**",
                subject : "ES CRM - New account created",
                htmlMessage : newAccountCreatedEmailTemplate.TransformText()
                );
        }
Пример #15
0
 private void InvokeEvent <T>(EventHandler <T> handler, T args) where T : NetMQMonitorEventArgs
 {
     if (EventReceived != null)
     {
         EventReceived.Invoke(this, args);
     }
     if (handler != null)
     {
         handler.Invoke(this, args);
     }
 }
Пример #16
0
        private void AdminPortTcpClient_MessageReceived(object sender, IAdminMessage e)
        {
            logger?.LogTrace($"{ServerInfo} Received message {e.MessageType} - {e}");
            StateRunners[Context.State].OnMessageReceived(e, Context);
            IAdminEvent?adminEvent = eventFactory.Create(e, Context);

            logger?.LogWarning($"{ServerInfo} adminEvent is null for {e.MessageType} {e}");
            if (adminEvent != null)
            {
                EventReceived?.Invoke(this, adminEvent);
            }
        }
        /// <inheritdoc/>
        public bool RaiseEventReceivedEvent(EventGridEventModel model)
        {
            if (string.IsNullOrWhiteSpace(model.EventType) || string.IsNullOrWhiteSpace(model.Subject))
            {
                return(false);
            }

            var eventGridViewerEventModel = _eventGridEventModelAdapter.Convert(model);

            EventReceived?.Invoke(this, new EventGridEventArgs(eventGridViewerEventModel));
            return(true);
        }
        public async Task HandleEvent <TEvent>(EventMessage <TEvent> message) where TEvent : class, IEvent
        {
            Delegate @delegate;

            if (!_subscribedEvents.TryGetValue(typeof(TEvent), out @delegate))
            {
                return;
            }

            EventReceived <TEvent> eventReceivedDelegate = (EventReceived <TEvent>)@delegate;

            await eventReceivedDelegate(message).ConfigureAwait(false);
        }
Пример #19
0
    public async Task DoesSomeStuff()
    {
        //arrange
        //(insert mocked interfaces to handler if required)
        var eventHandler = new EventReceivedHandler();
        var evt          = new EventReceived();

        //act
        await eventHandler.Handle(evt);

        //assert
        //.......
    }
Пример #20
0
 private void _run()
 {
     while (Running == true)
     {
         Poll();
         var datas = GetBufferedData();
         foreach (var state in datas)
         {
             EventReceived?.Invoke(new DMouseEventArgs(state));
         }
         Thread.Sleep(10);
     }
 }
Пример #21
0
        /// <summary>
        /// Refreshes the current Denon status.
        /// </summary>
        /// <param name="publishChanges">Indiactes if changes should be published or not.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task RefreshStatusAsync(bool publishChanges = false)
        {
            // Make all of the calls to get current status
            var status = new MainStatus();

            var mainZoneStatusTask      = _httpClient.GetDenonMainZoneStatusAsync();
            var secondaryZoneStatusTask = _httpClient.GetAllDenonSecondaryZonesStatusAsync(1);
            await Task.WhenAll(mainZoneStatusTask, secondaryZoneStatusTask).ConfigureAwait(false);

            var mainZoneStatus = await mainZoneStatusTask.ConfigureAwait(false);

            var secondaryZoneStatus = await secondaryZoneStatusTask.ConfigureAwait(false);

            status.Power        = mainZoneStatus.Power.Value.ToUpper() == "ON";
            status.Volume       = 80 + decimal.Parse(mainZoneStatus.MasterVolume.Value);
            status.Mute         = mainZoneStatus.Mute.Value.ToUpper() == "ON";
            status.Input        = mainZoneStatus.InputFuncSelect.Value;
            status.SurroundMode = mainZoneStatus.SurrMode.Value;

            foreach (var zone in secondaryZoneStatus)
            {
                var statusLite = new StatusLite
                {
                    Power  = zone.Value.Power.Value.ToUpper() == "ON",
                    Volume = 80 + decimal.Parse(zone.Value.MasterVolume.Value),
                    Mute   = zone.Value.Mute.Value.ToUpper() == "ON",
                    Input  = zone.Value.InputFuncSelect.Value
                };
                status.SecondaryZoneStatus.Add($"ZONE{zone.Key}", statusLite);
            }

            // Initialize state
            if (_status == null)
            {
                _status = status;
            }

            // Compare to current cached status
            var updates = CompareStatusObjects(_status, status);

            // If updated, publish changes
            if (publishChanges && updates.Count > 0)
            {
                foreach (var update in updates)
                {
                    EventReceived?.Invoke(this, new CommandEventArgs(update));
                }

                _status = status;
            }
        }
Пример #22
0
        public Task SetupQueueListenerAsync(
            string queueName,
            string topic,
            EventReceived callback,
            Type parameterType,
            string exchangeName = null)
        {
            EnsureArg.IsNotNullOrWhiteSpace(queueName, nameof(queueName));
            EnsureArg.IsNotNullOrWhiteSpace(topic, nameof(topic));
            EnsureArg.IsNotNull(callback, nameof(callback));
            EnsureArg.IsNotNull(parameterType, nameof(parameterType));

            LogSetupQueueListenerCalled(queueName, topic, parameterType, exchangeName);

            return(Task.Run(() =>
            {
                void CallbackInvoker(EventMessage eventMessage)
                {
                    LogReceivedCallback(queueName, topic, eventMessage.RoutingKey, eventMessage.JsonMessage);

                    object deserializedParameter;

                    try
                    {
                        deserializedParameter = JsonConvert.DeserializeObject(eventMessage.JsonMessage, parameterType);
                    }
                    catch (Exception exception)
                    {
                        LogFailedJsonConvert(queueName, topic, parameterType, eventMessage.JsonMessage, exception);
                        throw;
                    }

                    try
                    {
                        LogCallingCallback(queueName, topic);
                        callback(deserializedParameter, eventMessage.RoutingKey);
                        LogDoneCallingCallback(queueName, topic);
                    }
                    catch (Exception exeption)
                    {
                        LogFailedCallingCallback(queueName, topic, exeption);
                        throw;
                    }
                }

                _callbackRegistry.AddCallbackForQueue(queueName, topic, CallbackInvoker, exchangeName);

                LogSetupQueueListenerDone(queueName, topic, parameterType, exchangeName);
            }));
        }
Пример #23
0
        private IntPtr OnHookProc(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                try
                {
                    var mhs = Marshal.PtrToStructure <MouseHookStruct>(lParam);
                    EventReceived?.Invoke(wParam, new Point(mhs.pt.x, mhs.pt.y));
                }
                catch { }
            }

            return(CallNextHookEx(_hHook, nCode, wParam, lParam));
        }
Пример #24
0
        public void AddReceiver <TEvent>(string eventName, EventReceived <TEvent> eventReceived)
        {
            if (!Receivers.Keys.Contains(eventName))
            {
                lock (_mutex)
                {
                    if (!Receivers.Keys.Contains(eventName))
                    {
                        Receivers.Add(eventName, new List <EventReceived <string> >());
                    }
                }
            }

            Receivers[eventName].Add(payload => eventReceived(JsonConvert.DeserializeObject <TEvent>(payload)));
        }
Пример #25
0
        public async Task Handle(EventReceived <Deposit> @event, CancellationToken cancellationToken)
        {
            var partitionKey = new PartitionKey(@event.Event.OwnerId.ToString());

            var response = await _container.ReadItemAsync <CustomerDetails>(@event.Event.OwnerId.ToString(),
                                                                            partitionKey,
                                                                            null, cancellationToken);

            var customer   = response.Resource;
            var balance    = (customer.TotalBalance ?? new Money(Currency.CanadianDollar, 0));
            var newBalance = balance.Add(@event.Event.Amount.Value);

            var updatedCustomer = new CustomerDetails(customer.Id, customer.Firstname, customer.Lastname, customer.Email, customer.Accounts, newBalance);
            await _container.ReplaceItemAsync(updatedCustomer, @event.Event.OwnerId.ToString(), partitionKey, null, cancellationToken);
        }
        private async Task HandleEvent <TEvent>(EventReceived <TEvent> eventHandler, ConsumeContext <TEvent> context) where TEvent : class, IEvent
        {
            EventMessage <TEvent> message = _options.ContextManager.CreateEventMessage(context);

            _logger.LogVerbose(new { @event = message.Event.ToString(), eventType = typeof(TEvent).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt() }, arg => $"Received event of type {arg.eventType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Event: {arg.@event}");

            try
            {
                await eventHandler.Invoke(message).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(new { eventType = typeof(TEvent).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt(), @event = context.Message.ToString() }, ex, (arg, e) => $"Error while processing event of type {arg.eventType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Event: {arg.@event}. Error: {e.Message}");
                throw;
            }
        }
        public async Task Handle(EventReceived <AccountDeactivated> notification, CancellationToken cancellationToken)
        {
            Account account = await this._context.Accounts.FindAsync(notification.Event.AggregateId);

            if (account == null)
            {
                return;
            }

            account.IsActive       = false;
            account.LastModifiedBy = notification.Event.UserId;

            _context.Accounts.Update(account);

            await _context.SaveChangesAsync(cancellationToken);
        }
Пример #28
0
        protected override void WndProc(ref Message m)
        {
            _Lock.EnterReadLock();
            var isContained = Messages.Contains(m.Msg);

            _Lock.ExitReadLock();

            if (isContained)
            {
                _SynchronizationContext.Post((state) =>
                {
                    EventReceived?.Invoke((Message)state);
                }, m);
            }

            base.WndProc(ref m);
        }
Пример #29
0
        public Task SetupQueueListenerAsync <TParam>(
            string queueName,
            string topic,
            EventReceived <TParam> callback,
            string exchangeName = null)
        {
            EnsureArg.IsNotNullOrWhiteSpace(queueName, nameof(queueName));
            EnsureArg.IsNotNullOrWhiteSpace(topic, nameof(topic));
            EnsureArg.IsNotNull(callback, nameof(callback));

            return(SetupQueueListenerAsync(
                       queueName,
                       topic,
                       (input, receivedTopic) => callback((TParam)input, receivedTopic),
                       typeof(TParam),
                       exchangeName));
        }
Пример #30
0
        public void FireEventReceived(NetworkEvent networkEvent)
        {
            if (!IsPushEnabled)
            {
                return;
            }

            try
            {
                Trace($"{networkEvent.GetType().Name} received: {networkEvent}");
                EventReceived?.Invoke(networkEvent);
            }
            catch (Exception e)
            {
                Trace(e);
            }
        }