Exemplo n.º 1
0
        public async Task Consume(ConsumeContext <NotifyBookingSuccess> context)
        {
            _logger.Information($"{GetType().Name}: {context.Message.GetType().Name} received: {JsonSerializer.Serialize(context.Message)}");

            var booking = _bookingRepository.Get(context.Message.BookingId);

            var notifyBookingSuccess = new Notification.Contract.Messages.NotifyBookingSuccess
            {
                BookingId = booking.Id,
                Email     = booking.Email,
                Amount    = booking.Amount,
                Currency  = booking.Currency,
                Date      = DateTime.UtcNow
            };

            await Task.Delay(5000);

            _logger.Information($"{GetType().Name}: {context.Message.GetType().Name}: Sending IBookingSuccessNotified.");
            await _busControl.Send <IBookingSuccessNotified>(new { BookingId = booking.Id, DateTime.UtcNow });

            _logger.Information($"{GetType().Name}: {context.Message.GetType().Name}: Sending {notifyBookingSuccess.GetType().Name} : {JsonSerializer.Serialize(notifyBookingSuccess)}");
            await _kafkaProxy.SendMessage(_kafkaSettings.NotificationsTopic, notifyBookingSuccess);

            booking.Status    = BookingStatus.Succeeded;
            booking.SubStatus = BookingSubStatus.BookingSuccessNotified;

            _bookingRepository.Update(booking);
        }
Exemplo n.º 2
0
        public async Task CreateOrder(CreateOrderRequest createOrderRequest)
        {
            var createOrderCommand = new CreateOrderCommand()
            {
                Id         = Guid.NewGuid(),
                OrderCode  = createOrderRequest.OrderCode,
                OrderDate  = createOrderRequest.OrderDate,
                UserId     = createOrderRequest.UserId,
                TotalPrice = createOrderRequest.TotalPrice
            };

            await _busControl.Send(createOrderCommand, "create-order-command-queue");
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="imei"></param>
        /// <param name="dataReceived"></param>
        /// <param name="stream"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static async Task ParseTeltonikaData(TcpClient client, NetworkStream stream, byte[] buffer, string imei)
        {
            var currentImei = string.Empty;

            var gpsResult = new List <CreateTeltonikaGps>();

            while (true)
            {
                if (currentImei == string.Empty)
                {
                    currentImei = imei;
                    Console.WriteLine("IMEI received : " + currentImei);
                    Byte[] b = { 0x01 };
                    stream.Write(b, 0, 1);
                    var command = new CreateBoxCommand();
                    command.Imei = imei;
                    if (_bus != null)
                    {
                        await _bus.Send(command);
                    }
                }
                else
                {
                    int dataNumber = Convert.ToInt32(buffer.Skip(9).Take(1).ToList()[0]);
                    while (dataNumber > 0)
                    {
                        var parser = new DevicesParser();
                        gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei));
                        dataNumber--;
                    }

                    await stream.WriteAsync(new byte[] { 0x00, 0x00, 0x00, 0x01 }, 0, 4).ConfigureAwait(false);
                }

                if (!gpsResult.Any() && imei.Any())
                {
                    continue;
                }
                foreach (var gpSdata in gpsResult)
                {
                    if (_bus != null)
                    {
                        await _bus.Send(gpSdata);
                    }
                }
                break;
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("====== Starting Publisher ======");

            IBusControl bus = ConfigureBus();

            bus.Start();

            for (;;)
            {
                var consoleKeyInfo = Console.ReadKey(true);
                if (consoleKeyInfo.Key == ConsoleKey.Enter)
                {
                    break;
                }

                if (consoleKeyInfo.Key == ConsoleKey.E)
                {
                    //.. send email
                    var messageId = Guid.NewGuid().ToString();
                    Console.WriteLine($"Order Created event sent: {messageId}");
                    bus.Send(new OrderCreated()
                    {
                        EmailId = messageId,
                        Body    = "This is an email body",
                        From    = "*****@*****.**",
                        To      = "*****@*****.**"
                    });
                }
            }
        }
        public void UploadAvatar(Guid id, Stream file)
        {
            var customer = _customers.GetValueOrDefault(id);

            if (customer == null)
            {
                throw new Exception("Customer not found.");
            }

            var avatarId = _fileServerService.Upload(file);

            var avatar = new CustomerImageModel()
            {
                CustomerId = id,
                AvatarId   = avatarId,
                Size       = Math.Round((decimal)file.Length / (1024 * 1024), 2)
            };

            customer.Avatar = avatar;

            _bus.Send(new ImageResizeMessage()
            {
                Id     = avatarId,
                Height = 64,
                Width  = 64
            });
        }
Exemplo n.º 6
0
 public void Execute() => base.Execute(() =>
 {
     var response = _busControl.Send <ISouthRequest, ISouthResponse>(new SouthRequest {
         Reason = "ping"
     });
     _healthCheckService.SetSouthLatestInfo(response);
 });
Exemplo n.º 7
0
 public async Task SendAsync(string[] PhoneNumbers, string code)
 {
     await _bus.Send <SendMobileCodeCommand>(new
     {
         PhoneNumbers = PhoneNumbers,
         Code         = code,
     });
 }
Exemplo n.º 8
0
        public static async Task SendBadTestMessage(this IBusControl bus)
        {
            await bus.Publish(new BadConsumerRegTestMessage()
            {
            });

            await bus.Send(new BadConsumerRegTestMessage()
            {
            });
        }
Exemplo n.º 9
0
        private async Task DoWork(CancellationToken stoppingToken)
        {
            var config = new ConsumerConfig
            {
                GroupId          = ConsumerGroup,
                BootstrapServers = KafkaServers,
                AutoOffsetReset  = AutoOffsetReset.Earliest
            };

            _logger.Information($"{GetType().Name}: Creating consumer for '{ConsumerGroup}' pointed at '{KafkaServers}'.");
            using var consumer = new ConsumerBuilder <Ignore, string>(config).Build();

            _logger.Information($"{GetType().Name}: Subscribing the consumer to topic '{KafkaTopic}'.");
            consumer.Subscribe(KafkaTopic);

            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        _logger.Information($"{GetType().Name}: Consuming next message.");
                        var result = consumer.Consume(stoppingToken);
                        _logger.Information($"{GetType().Name}: Consumed message '{result.Message.Value}' at offset '{result.TopicPartitionOffset}'.");

                        if (_messageDeserializer.TryDeserializeEvent(result.Message.Value, out BookingCreated bookingCreated))
                        {
                            _logger.Information($"{GetType().Name}: Message {result.Message.Value} is recognized by {GetType().Name} as {nameof(BookingCreated)} event and will be processed.");

                            await _busControl.Send <IBookingCreated>(
                                new
                            {
                                bookingCreated.BookingId,
                                DateTime.UtcNow
                            }, stoppingToken);

                            _logger.Information($"{GetType().Name}: Message {result.Message.Value} was processed.");

                            continue;
                        }

                        _logger.Information($"{GetType().Name}: Message {result.Message.Value} is not recognized by {GetType().Name} and will be skipped.");
                    }
                    catch (ConsumeException e)
                    {
                        _logger.Error($"{GetType().Name}: Error occurred: {e.Error.Reason}.");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // Ensure the consumer leaves the group cleanly and final offsets are committed.
                consumer.Close();
            }
        }
Exemplo n.º 10
0
        public void SendEvent(IEvent @event)
        {
            var message = new BusMessage
            {
                MessageType = @event.GetType().Name
            };

            message.SetData(@event);

            _Bus.Send(message);
        }
Exemplo n.º 11
0
 public async Task SendCreateRecordMessageAsync(CreateRecordMessageBusMessage messageBusMessage)
 {
     try
     {
         await _busControl.Send(messageBusMessage);
     }
     catch (Exception exception)
     {
         _logger.Log(LogLevel.Critical, exception, exception.Message);
     }
 }
Exemplo n.º 12
0
        public Task <User> Handle(User user)
        {
            user.Id = Guid.NewGuid();

            _busControl.Send(new AddUserCommand
            {
                User = user
            });

            return(Task.FromResult(user));
        }
Exemplo n.º 13
0
        public async Task <MessageViewModel> Handle(CreateMessage request, CancellationToken cancellationToken)
        {
            await _busControl.Send(new Message
            {
                Date = DateTime.UtcNow,
                From = "Api",
                Text = request.Message.Text
            });

            return(new MessageViewModel());
        }
Exemplo n.º 14
0
        private void BtnSendNotifyMsg_Click(object sender, EventArgs e)
        {
            _bus.Send(new BizSystemNotifyMsg
            {
                SystemId        = txtNotifyBizSystemId.Text,
                Category        = int.Parse(txtNotifyMsgCategory.Text),
                Content         = txtNotifyMsgContent.Text,
                ReceiverUserIds = txtNotifyMsgUserIds.Text.Split(',').Select(x => new Guid(x)).ToArray()
            });

            MessageBox.Show("发送成功");
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            IBusControl bus = Bus.Factory.CreateUsingRabbitMq(cfg => {
                cfg.Host(new Uri("rabbitmq://localhost/MassTransit_Demo"), c => {
                    c.Username("root");
                    c.Password("root#123");
                });
            });

            bus.Start();
            Console.WriteLine("输入q退出,其他 发送消息");
            while (true)
            {
                var read = Console.ReadLine();
                if (read.ToLower().Equals("q"))
                {
                    break;
                }

                bus.Send(new SendMessage
                {
                    Message = read
                }).ContinueWith(task =>
                {
                    Console.WriteLine($"发送消息:{read}");
                });

                bus.Send <ISyncMessage>(new
                {
                    Message = read
                }).ContinueWith(task =>
                {
                    Console.WriteLine($"发送消息:{read}");
                });
            }

            bus.Stop();
        }
Exemplo n.º 16
0
        public async Task Run()
        {
            string data = Guid.NewGuid().ToString();

            await _busControl.Publish(new SomeEvent()
            {
                Data = data
            });

            await _busControl.Send(new SomeCommand()
            {
                Data = data
            }, "superb_command_queue");
        }
Exemplo n.º 17
0
        public async void SendMessageCommand(Message message)
        {
            try
            {
                // Important! The bus must be started before using it!
                await _busControl.StartAsync();

                await _busControl.Send <Message>(message);
            }
            finally
            {
                await _busControl.StopAsync();
            }
        }
Exemplo n.º 18
0
        public async Task <string> SendAsync(string phoneNumber)
        {
            var code = (new Random().Next(1000, 9999)).ToString();

            await _simpleKeyValueService.AddOrUpdate(
                SimpleKeyValueServiceContainerName, phoneNumber, code);

            await _bus.Send <SendMobileCodeCommand>(new
            {
                PhoneNumbers = new string[] { phoneNumber },
                Code         = code,
            });

            return(code);
        }
Exemplo n.º 19
0
        public async Task DistributeAsync(CancellationToken cancellationToken = default)
        {
            while (_integrationMessageQueue.TryDequeue(out var result))
            {
                switch (result)
                {
                case IIntegrationEvent _:
                    await _busControl.Publish(result, result.GetType(), cancellationToken);

                    break;

                case IIntegrationCommand _:
                    await _busControl.Send(result, result.GetType(), cancellationToken);

                    break;

                default:
                    throw new ArgumentException($"{result.GetType()} is not expected type");
                }
            }
        }
Exemplo n.º 20
0
 private void CreateOrder(OrderModel orderModel)
 {
     _bus.Send(orderModel).Wait();
 }
        public async Task <CommandResult <TokenViewModel> > Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            var exit = new CommandResult <TokenViewModel>();

            var user = new User()
            {
                Email              = request.Email,
                Name               = request.Name,
                Type               = request.Type,
                Active             = true,
                DocumentIdentifier = request.DocumentIdentifier,
                PhoneNumber        = request.PhoneNumber,
                PrimaryLocation    = new Location()
                {
                    Address       = request.Address,
                    AddressNumber = request.AddressNumber,
                    Burgh         = request.Burgh,
                    Cep           = request.Cep,
                    Complement    = request.Complement,
                    CityId        = request.CityId,
                    Latitude      = request.Latitude,
                    Longitude     = request.Longitude
                }
            };

            var result = await _userManager.CreateAsync(user, request.Password);

            if (!result.Succeeded)
            {
                _notificationContext.PushNotifications(result.Errors.ExtractNotificationsFromIdentityErrors());

                return(exit);
            }

            if (request.Type == UserType.Client)
            {
                await _clientRepository.Add(user.Client = new ClientUser()
                {
                    BirthDate = request.BirthDate,
                    KiloMetersSearchRadius = request.KiloMetersSearchRadius,
                    Rg     = request.Rg,
                    UserId = user.Id
                });
            }
            else
            {
                await _providerRepository.Add(user.Provider = new ProviderUser()
                {
                    BrazilianInscricaoEstadual = request.BrazilianInscricaoEstadual,
                    LicenseValidity            = request.LicenseValidity,
                    UserId = user.Id
                });
            }

            await _busControl.Send(new UserCreatedEvent()
            {
                Name          = user.Name,
                Address       = request.Address,
                AddressNumber = request.AddressNumber,
                BrazilianInscricaoEstadual = request.BrazilianInscricaoEstadual,
                Burgh              = request.Burgh,
                Cep                = request.Cep,
                Longitude          = request.Longitude,
                Latitude           = request.Latitude,
                CityId             = request.CityId,
                Complement         = request.Complement,
                DocumentIdentifier = request.DocumentIdentifier,
                Email              = request.Email,
                Id = user.Id,
                LicenseValidity = request.LicenseValidity,
                PhoneNumber     = request.PhoneNumber,
                Rg        = request.Rg,
                BirthDate = request.BirthDate,
                Type      = request.Type
            });

            return(exit.ReturningSuccess(await _service.GenerateToken(user)));
        }
Exemplo n.º 22
0
 public Task SendAsync <T>(T obj, CancellationToken token = default) where T : class, new()
 {
     return(_bus.Send(obj, token));
 }
Exemplo n.º 23
0
 public Task SendMessage(Message message)
 {
     return(_Bus.Send(message));
 }
Exemplo n.º 24
0
 public Task Send <TMessage>(TMessage message) where TMessage : class
 {
     return(_busControl.Send <TMessage>(message));
 }
Exemplo n.º 25
0
 protected override async Task HandleAsync(IIntegrationCommand payload, CancellationToken cancellationToken)
 {
     await _busControl.Send(payload, payload.GetType(), cancellationToken);
 }
 public Task NewOrderSendSample(INewOrder msg)
 {
     return(_busControl.Send(msg));
 }
Exemplo n.º 27
0
 public async Task SendAsync <T>(T commandMessage) where T : class, ICommand
 {
     ValidateContract <T>((T)commandMessage);
     await _massTransitBus.Send(commandMessage).ConfigureAwait(false);
 }