Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();

            var eventHandlerExecutionContext = new MessageHandlerContext(services,
                                                                         sc => sc.BuildServiceProvider());

            services.AddSingleton <IMessageHandlerContext>(eventHandlerExecutionContext);

            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };

            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IMessageHandlerContext>(),
                                                                         EdaHelper.RMQ_EVENT_EXCHANGE,
                                                                         queueName: typeof(Startup).Namespace));

            var mongoServer   = Configuration["mongo:server"];
            var mongoDatabase = Configuration["mongo:database"];
            var mongoPort     = Convert.ToInt32(Configuration["mongo:port"]);

            services.AddSingleton <IDataAccessObject>(serviceProvider => new MongoDataAccessObject(mongoDatabase, mongoServer, mongoPort));

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Configure data access component.
            var mongoServer   = Configuration["mongo:server"];
            var mongoDatabase = Configuration["mongo:database"];
            var mongoPort     = Convert.ToInt32(Configuration["mongo:port"]);

            services.AddSingleton <IDataAccessObject>(serviceProvider => new MongoDataAccessObject(mongoDatabase, mongoServer, mongoPort));

            var messageHandlerExecutionContext = new MessageHandlerContext(services,
                                                                           sc => sc.BuildServiceProvider());

            services.AddSingleton <IMessageHandlerContext>(messageHandlerExecutionContext);

            // Configure RabbitMQ.
            var rabbitServer      = Configuration["rabbit:server"];
            var connectionFactory = new ConnectionFactory {
                HostName = rabbitServer
            };

            services.AddSingleton <ICommandBus>(sp => new RabbitMQCommandBus(connectionFactory,
                                                                             sp.GetRequiredService <ILogger <RabbitMQCommandBus> >(),
                                                                             sp.GetRequiredService <IMessageHandlerContext>(),
                                                                             EdaHelper.RMQ_COMMAND_EXCHANGE,
                                                                             queueName: typeof(Startup).Namespace));
        }
Ejemplo n.º 3
0
        public void InsertDeviceNotification(string deviceGuid, JObject notification)
        {
            if (string.IsNullOrEmpty(deviceGuid))
            {
                throw new WebSocketRequestException("Please specify valid deviceGuid");
            }

            if (notification == null)
            {
                throw new WebSocketRequestException("Please specify notification");
            }

            var device = DataContext.Device.Get(deviceGuid);

            if (device == null || !IsDeviceAccessible(device, "CreateDeviceNotification"))
            {
                throw new WebSocketRequestException("Device not found");
            }

            var notificationEntity = GetMapper <DeviceNotification>().Map(notification);

            notificationEntity.Device = device;
            Validate(notificationEntity);

            var context = new MessageHandlerContext(notificationEntity, CurrentUser);

            _messageManager.HandleNotification(context);

            notification = GetMapper <DeviceNotification>().Map(notificationEntity, oneWayOnly: true);
            SendResponse(new JProperty("notification", notification));
        }
Ejemplo n.º 4
0
        public void UpdateDeviceCommand(int commandId, JObject command)
        {
            if (commandId == 0)
            {
                throw new WebSocketRequestException("Please specify valid commandId");
            }

            if (command == null)
            {
                throw new WebSocketRequestException("Please specify command");
            }

            var commandEntity = DataContext.DeviceCommand.Get(commandId);

            if (commandEntity == null || commandEntity.DeviceID != CurrentDevice.ID)
            {
                throw new WebSocketRequestException("Device command not found");
            }

            GetMapper <DeviceCommand>().Apply(commandEntity, command);
            commandEntity.Device = CurrentDevice;
            Validate(commandEntity);

            var context = new MessageHandlerContext(commandEntity, null);

            _messageManager.HandleCommandUpdate(context);

            SendSuccessResponse();
        }
Ejemplo n.º 5
0
        public PayloadDescriptor Create(object message, MessageHandlerContext context, Dictionary <string, string> headers)
        {
            var metadata = new Metadata(headers)
            {
                CorrelationId = context.CorrelationId,
                CausationId   = context.MessageId
            };

            return(Create(message, metadata));
        }
Ejemplo n.º 6
0
        public Task Handle(StudentEnrolled message, MessageHandlerContext context)
        {
            _logger.LogDebug($@"{this.GetType().Name} handled: {{@Message}}", message);

            _stats.Consume();

            _logger.LogInformation("{Stats}", _stats.ToString());

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Invoked when a new notification is inserted.
        /// </summary>
        /// <param name="context">MessageHandlerContext object.</param>
        public override void NotificationInserted(MessageHandlerContext context)
        {
            var parameters = JObject.Parse(context.Notification.Parameters);
            var deviceStatus = (string)parameters["status"];
            if (string.IsNullOrEmpty(deviceStatus))
                throw new Exception("Device status notification is missing required 'status' parameter");

            var device = _deviceRepository.Get(context.Device.ID);
            device.Status = deviceStatus;
            _deviceRepository.Save(device);
        }
Ejemplo n.º 8
0
        override protected void onRecieve(string msg, MessageHandlerContext context)
        {
            double result;

            if (double.TryParse(msg, out result))
            {
                Console.WriteLine($"{calDic[context.Properties.CorrelationId]} = {msg}");
            }
            else
            {
                Console.WriteLine($"Cannot calculate: {calDic[context.Properties.CorrelationId]} ");
            }
        }
Ejemplo n.º 9
0
        public JObject Post(string deviceGuid, JObject json)
        {
            var device = GetDeviceEnsureAccess(deviceGuid);

            var notification = Mapper.Map(json);

            notification.Device = device;
            Validate(notification);

            var context = new MessageHandlerContext(notification, CallContext.CurrentUser);

            _messageManager.HandleNotification(context);

            return(Mapper.Map(notification, oneWayOnly: true));
        }
        /// <summary>
        /// Invoked when a new notification is inserted.
        /// </summary>
        /// <param name="context">MessageHandlerContext object.</param>
        public override void NotificationInserted(MessageHandlerContext context)
        {
            var parameters   = JObject.Parse(context.Notification.Parameters);
            var deviceStatus = (string)parameters["status"];

            if (string.IsNullOrEmpty(deviceStatus))
            {
                throw new Exception("Device status notification is missing required 'status' parameter");
            }

            var device = _deviceRepository.Get(context.Device.ID);

            device.Status = deviceStatus;
            _deviceRepository.Save(device);
        }
Ejemplo n.º 11
0
 override protected void onRecieve(string msg, MessageHandlerContext context)
 {
     try {
         var msgChips = msg.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
         if (msgChips[0].ToLower() == "-")
         {
             double a      = Convert.ToDouble(msgChips[1]);
             double b      = Convert.ToDouble(msgChips[2]);
             double result = a - b;
             context.SendBack(result.ToString());
         }
     } catch (Exception e) {
         Debug.WriteLine("ERROR: " + e.Message);
         context.SendBack("invalid message content");
     }
 }
        public JObject Post(string deviceGuid, JObject json)
        {
            var device = GetDeviceEnsureAccess(deviceGuid);

            var command = Mapper.Map(json);

            command.Device = device;
            command.UserID = CallContext.CurrentUser.ID;
            Validate(command);

            var context = new MessageHandlerContext(command, CallContext.CurrentUser);

            _messageManager.HandleCommand(context);

            return(Mapper.Map(command, oneWayOnly: true));
        }
        /// <summary>
        /// Invoked when a new notification is inserted.
        /// </summary>
        /// <param name="context">MessageHandlerContext object.</param>
        public override void NotificationInserted(MessageHandlerContext context)
        {
            var parameters = JObject.Parse(context.Notification.Parameters);
            var equipmentCode = (string)parameters["equipment"];
            if (string.IsNullOrEmpty(equipmentCode))
                throw new Exception("Equipment notification is missing required 'equipment' parameter");

            parameters.Remove("equipment");
            var equipment = _deviceEquipmentRepository.GetByDeviceAndCode(context.Device.ID, equipmentCode);
            if (equipment == null)
            {
                equipment = new DeviceEquipment(equipmentCode, context.Notification.Timestamp, context.Device);
            }
            equipment.Timestamp = context.Notification.Timestamp;
            equipment.Device = context.Device;
            equipment.Parameters = parameters.ToString();
            _deviceEquipmentRepository.Save(equipment);
        }
Ejemplo n.º 14
0
        public void InsertDeviceNotification(JObject notification)
        {
            if (notification == null)
            {
                throw new WebSocketRequestException("Please specify notification");
            }

            var notificationEntity = GetMapper <DeviceNotification>().Map(notification);

            notificationEntity.Device = CurrentDevice;
            Validate(notificationEntity);

            var context = new MessageHandlerContext(notificationEntity, null);

            _messageManager.HandleNotification(context);

            notification = GetMapper <DeviceNotification>().Map(notificationEntity, oneWayOnly: true);
            SendResponse(new JProperty("notification", notification));
        }
        public void Put(string deviceGuid, int id, JObject json)
        {
            var device = GetDeviceEnsureAccess(deviceGuid);

            var command = DataContext.DeviceCommand.Get(id);

            if (command == null || command.DeviceID != device.ID)
            {
                ThrowHttpResponse(HttpStatusCode.NotFound, "Device command not found!");
            }

            Mapper.Apply(command, json);
            command.Device = device;
            Validate(command);

            var context = new MessageHandlerContext(command, CallContext.CurrentUser);

            _messageManager.HandleCommandUpdate(context);
        }
Ejemplo n.º 16
0
        public void UpdateDeviceCommand(string deviceGuid, int commandId, JObject command)
        {
            if (string.IsNullOrEmpty(deviceGuid))
            {
                throw new WebSocketRequestException("Please specify valid deviceGuid");
            }

            if (commandId == 0)
            {
                throw new WebSocketRequestException("Please specify valid commandId");
            }

            if (command == null)
            {
                throw new WebSocketRequestException("Please specify command");
            }

            var device = DataContext.Device.Get(deviceGuid);

            if (device == null || !IsDeviceAccessible(device, "UpdateDeviceCommand"))
            {
                throw new WebSocketRequestException("Device not found");
            }

            var commandEntity = DataContext.DeviceCommand.Get(commandId);

            if (commandEntity == null || commandEntity.DeviceID != device.ID)
            {
                throw new WebSocketRequestException("Device command not found");
            }

            GetMapper <DeviceCommand>().Apply(commandEntity, command);
            commandEntity.Device = device;
            Validate(commandEntity);

            var context = new MessageHandlerContext(commandEntity, CurrentUser);

            _messageManager.HandleCommandUpdate(context);

            SendSuccessResponse();
        }
Ejemplo n.º 17
0
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();
            services.AddOptions();

            // Configure event store.
            services.Configure <PostgreSqlConfig>(Configuration.GetSection("postgresql"));
            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(Configuration["postgresql:connectionString"],
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            // Configure data access component.
            var mongoServer   = Configuration["mongo:server"];
            var mongoDatabase = Configuration["mongo:database"];
            var mongoPort     = Convert.ToInt32(Configuration["mongo:port"]);

            services.AddSingleton <IDataAccessObject>(serviceProvider => new MongoDataAccessObject(mongoDatabase, mongoServer, mongoPort));

            // Configure event handlers.
            var eventHandlerExecutionContext = new MessageHandlerContext(services,
                                                                         sc => sc.BuildServiceProvider());

            services.AddSingleton <IMessageHandlerContext>(eventHandlerExecutionContext);

            // Configure RabbitMQ.
            var rabbitServer      = Configuration["rabbit:server"];
            var connectionFactory = new ConnectionFactory {
                HostName = rabbitServer
            };

            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IMessageHandlerContext>(),
                                                                         EdaHelper.RMQ_EVENT_EXCHANGE,
                                                                         queueName: typeof(Startup).Namespace));

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
        /// <summary>
        /// Invoked when a new notification is inserted.
        /// </summary>
        /// <param name="context">MessageHandlerContext object.</param>
        public override void NotificationInserted(MessageHandlerContext context)
        {
            var parameters    = JObject.Parse(context.Notification.Parameters);
            var equipmentCode = (string)parameters["equipment"];

            if (string.IsNullOrEmpty(equipmentCode))
            {
                throw new Exception("Equipment notification is missing required 'equipment' parameter");
            }

            parameters.Remove("equipment");
            var equipment = _deviceEquipmentRepository.GetByDeviceAndCode(context.Device.ID, equipmentCode);

            if (equipment == null)
            {
                equipment = new DeviceEquipment(equipmentCode, context.Notification.Timestamp, context.Device);
            }
            equipment.Timestamp  = context.Notification.Timestamp;
            equipment.Device     = context.Device;
            equipment.Parameters = parameters.ToString();
            _deviceEquipmentRepository.Save(equipment);
        }
Ejemplo n.º 19
0
        public async Task HandleAsync(object messageToProcess)
        {
            var handlerType = typeof(IMessageHandler <>).MakeGenericType(messageToProcess.GetType());
            var instance    = _serviceProvider.GetService(handlerType);

            if (instance == null)
            {
                return;
            }

            var method = instance.GetType().GetMethod("Handle",
                                                      new[] { typeof(MessageHandlerContext), messageToProcess.GetType() });

            if (method == null)
            {
                throw new InvalidOperationException(
                          $"Opps, did not find method 'Handle' in type '{instance.GetType()}'.");
            }

            var   context = new MessageHandlerContext();
            var   task    = (Task)method.Invoke(instance, new[] { context, messageToProcess });
            await task;
        }
Ejemplo n.º 20
0
        public void InsertDeviceCommand(string deviceGuid, JObject command)
        {
            if (string.IsNullOrEmpty(deviceGuid))
            {
                throw new WebSocketRequestException("Please specify valid deviceGuid");
            }

            if (command == null)
            {
                throw new WebSocketRequestException("Please specify command");
            }

            var device = DataContext.Device.Get(deviceGuid);

            if (device == null || !IsDeviceAccessible(device, "CreateDeviceCommand"))
            {
                throw new WebSocketRequestException("Device not found");
            }

            var commandEntity = GetMapper <DeviceCommand>().Map(command);

            commandEntity.Device = device;
            commandEntity.UserID = CurrentUser.ID;
            Validate(commandEntity);

            var context = new MessageHandlerContext(commandEntity, CurrentUser);

            _messageManager.HandleCommand(context);
            if (!context.IgnoreMessage)
            {
                _commandSubscriptionManager.Subscribe(Connection, commandEntity.ID);
            }

            command = GetMapper <DeviceCommand>().Map(commandEntity, oneWayOnly: true);
            SendResponse(new JProperty("command", command));
        }
Ejemplo n.º 21
0
        public Task Handle(TestEvent message, MessageHandlerContext context)
        {
            _logger.LogInformation($@"{this.GetType().Name} handled: {{@Message}}", message);

            return(Task.CompletedTask);
        }
Ejemplo n.º 22
0
 public void VerifyAccountFundsExpiredEventNotPublished()
 {
     MessageHandlerContext.Verify(c => c.Publish(It.IsAny <AccountFundsExpiredEvent>(), It.IsAny <PublishOptions>()),
                                  Times.Never);
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Produce a <paramref name="message"/> on Kafka
 /// </summary>
 /// <param name="message">The message</param>
 /// <param name="context">Context from the consumer</param>
 public async Task Produce(object message, MessageHandlerContext context)
 {
     await Produce(message, context, new Dictionary <string, string>());
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Produce a <paramref name="message"/> on Kafka
 /// </summary>
 /// <param name="message">The message</param>
 /// <param name="context">Context from the consumer</param>
 /// <param name="headers">The message headers</param>
 public async Task Produce(object message, MessageHandlerContext context, Dictionary <string, string> headers)
 {
     var payloadDescriptor = _payloadDescriptorFactory.Create(message, context, headers);
     await _kafkaProducer.Produce(payloadDescriptor);
 }
Ejemplo n.º 25
0
        ///<inheritdoc/>
        public Task Dispatch <TMessage>(TMessage message) where TMessage : IMessage
        {
            var context = new MessageHandlerContext();

            return(Dispatch(message, context));
        }
Ejemplo n.º 26
0
 public void VerifyAccountFundsExpiredEventPublished()
 {
     MessageHandlerContext.Verify(c =>
                                  c.Publish(It.Is <AccountFundsExpiredEvent>(e => e.AccountId == ExpectedAccountId), It.IsAny <PublishOptions>()),
                                  Times.Once);
 }
Ejemplo n.º 27
0
 public Task Handle(FooMessage message, MessageHandlerContext context)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 28
0
 public Task Handle(MessageHandlerContext context, MyMessage message)
 {
     Console.WriteLine("We got called!");
     return(Task.CompletedTask);
 }
Ejemplo n.º 29
0
            public async Task Handle(DummyMessage message, MessageHandlerContext context)
            {
                await _scopeSpy.DoSomethingAsync();

                await _repository.PerformActionAsync();
            }
Ejemplo n.º 30
0
 public Task Handle(TMessage message, MessageHandlerContext context)
 {
     _onHandle?.Invoke();
     return(Task.CompletedTask);
 }
            public Task Handle(DummyMessage message, MessageHandlerContext context)
            {
                LastHandledMessage = message;

                return(Task.CompletedTask);
            }
Ejemplo n.º 32
0
 public Task Handle(object message, MessageHandlerContext context)
 {
     throw new ExpectedException();
 }