Example #1
0
        public void FromPublisherConfig_NullOrEmptyRoutingKey_Throws(string routingKey)
        {
            var factory = new RabbitMQConnectionFactory();
            var cfg = GetPublisherConfig("host", "user", "password", "vHost", "exchange", routingKey);

            Assert.Throws<ArgumentException>(() => factory.From(cfg));
        }
Example #2
0
 /// <summary>
 /// Открывает соединение с RabbitMQ
 /// </summary>
 private void OpenRabbitMQConnection()
 {
     Connection        = RabbitMQConnectionFactory.CreateConnection();
     RabbitChannel     = Connection.CreateModel();
     _rabbitProperties = RabbitChannel.CreateBasicProperties();
     _rabbitProperties.SetPersistent(true);
 }
Example #3
0
        public void FromConsumerConfig_NullOrEmptyQueueName_Throws(string name)
        {
            var factory = new RabbitMQConnectionFactory();
            var cfg = GetConsumerConfig("host", "user", "password", "vHost", name, "exchange", "routingKey");

            Assert.Throws<ArgumentException>(() => factory.From(cfg));
        }
Example #4
0
        private static void Main()
        {
            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            // Appsettings is renamed because of an issue where the project loaded another appsettings.json
            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettingsnotificationsystem.json", true, true)
                                           .AddJsonFile($"appsettingsnotificationsystem.{environmentName}.json", true, true)
                                           .AddEnvironmentVariables()
                                           .Build();
            Config config = configuration.GetSection("App").Get <Config>();

            IRabbitMQConnectionFactory connectionFactory = new RabbitMQConnectionFactory(config.RabbitMQ.Hostname, config.RabbitMQ.Username, config.RabbitMQ.Password);

            RabbitMQSubscriber subscriber = new RabbitMQSubscriber(connectionFactory);
            IModel             channel    = subscriber.SubscribeToSubject("EMAIL");

            RabbitMQListener listener = new RabbitMQListener(channel);

            // inject your notification service here
            ISendGridClient       sendGridClient      = new SendGridClient(config.SendGrid.ApiKey);
            INotificationService  notificationService = new EmailSender(sendGridClient, config.SendGrid.EmailFrom, config.SendGrid.SandboxMode);
            EventingBasicConsumer consumer            = listener.CreateConsumer(notificationService);

            listener.StartConsumer(consumer, "EMAIL");
            Console.ReadLine();
        }
        public void CanSendAndReceiveMessage()
        {
            //Arrange
            const string routingKey = nameof(routingKey);
            var connectionFactory = new RabbitMQConnectionFactory(CONNECTION_STRING);
            using var connection = connectionFactory.CreateConnection(nameof(IntegrationTests));
            using var consumer = connection.CreateConsumer(routingKey);
            using var publisher = connection.CreatePublisher(routingKey);
            var expected = new byte[3] { 0x01, 0x02, 0x03 };
            byte[] actual = null;
            var mre = new ManualResetEvent(false);
            void onMessageReceived(object sender, MessageReceivedEventArgs e)
            {
                actual = e?.Body;
                mre.Set();
            }

            //Act
            consumer.RegisterConsumer(onMessageReceived);
            publisher.SendMessage(expected);
            var flagged = mre.WaitOne(Timeout.Infinite);

            //Assert
            Assert.True(flagged);
            Assert.Equal(expected, actual);
        }
Example #6
0
        private void Redeliver(byte[] message, int redeliveredCount)
        {
            RabbitMQConnectionFactory Instance = RabbitMQConnectionFactory.RabbitMQConnectionFactoryInstance;

            Instance.CreateFanoutExchange("SendMessages", true, false);
            bool isPublished = Instance.PublishMessage("SendMessages", "", false, null, message, redeliveredCount);
        }
Example #7
0
        private void SendEmail(string email, string name, int storedEmailId)
        {
            var sendEmailMessage = new SendEmailMessage()
            {
                From = new EmailContact
                {
                    Name  = _emailParametersProvider.DocumentEmailSenderName,
                    Email = _emailParametersProvider.DocumentEmailSenderAddress
                },

                To = new List <EmailContact>
                {
                    new EmailContact
                    {
                        Name  = name,
                        Email = email
                    }
                },

                Subject  = MailSubject,
                TextPart = MailTextPart,
                HTMLPart = MailTextPart,
                Payload  = new EmailPayload
                {
                    Id         = storedEmailId,
                    Trackable  = true,
                    InstanceId = _instanceId
                }
            };

            var emailAttachments = new List <EmailAttachment>();

            foreach (var attachment in ObservableAttachments)
            {
                emailAttachments.Add(new EmailAttachment
                {
                    ContentType   = MimeMapping.GetMimeMapping(attachment.FileName),
                    Filename      = attachment.FileName,
                    Base64Content = Convert.ToBase64String(attachment.ByteFile)
                });
            }

            sendEmailMessage.Attachments = emailAttachments;

            var serializedMessage = JsonSerializer.Serialize(sendEmailMessage);
            var sendingBody       = Encoding.UTF8.GetBytes(serializedMessage);

            var logger            = new Logger <RabbitMQConnectionFactory>(new NLogLoggerFactory());
            var connectionFactory = new RabbitMQConnectionFactory(logger);
            var connection        = connectionFactory.CreateConnection(_configuration.MessageBrokerHost, _configuration.MessageBrokerUsername,
                                                                       _configuration.MessageBrokerPassword, _configuration.MessageBrokerVirtualHost);
            var channel    = connection.CreateModel();
            var properties = channel.CreateBasicProperties();

            properties.Persistent = true;

            channel.BasicPublish(_configuration.EmailSendExchange, _configuration.EmailSendKey, false, properties, sendingBody);
        }
Example #8
0
 public MailjetEventsDistributeController(ILogger <MailjetEventsDistributeController> logger, IInstanceData instanceData,
                                          RabbitMQConnectionFactory queueConnectionFactory, IConfiguration configuration)
 {
     _logger                 = logger ?? throw new ArgumentNullException(nameof(logger));
     _configuration          = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _instanceData           = instanceData ?? throw new ArgumentNullException(nameof(instanceData));
     _queueConnectionFactory = queueConnectionFactory ?? throw new ArgumentNullException(nameof(queueConnectionFactory));
     _mailEventExchange      = configuration.GetSection(_queuesConfigurationSection).GetValue <string>(_emailStatusUpdateExchangeParameter);
     _mailEventKey           = configuration.GetSection(_queuesConfigurationSection).GetValue <string>(_emailStatusUpdateKeyParameter);
 }
Example #9
0
        public void NotifyEmployee(string orderNumber, string signature)
        {
            var configuration = _uow.GetAll <InstanceMailingConfiguration>().FirstOrDefault();

            string messageText = $"Оповещение о пришедшей оплате с неверной подписью: {signature}" +
                                 $"для платежа по заказу №{orderNumber}";

            var sendEmailMessage = new SendEmailMessage
            {
                From = new EmailContact
                {
                    Name  = _emailParametersProvider.DocumentEmailSenderName,
                    Email = _emailParametersProvider.DocumentEmailSenderAddress
                },

                To = new List <EmailContact>
                {
                    new EmailContact
                    {
                        Name  = "Уважаемый пользователь",
                        Email = _emailParametersProvider.InvalidSignatureNotificationEmailAddress
                    }
                },

                Subject = $"Неккоректная подпись успешной оплаты заказа №{orderNumber}",

                TextPart = messageText,
                HTMLPart = messageText,
                Payload  = new EmailPayload
                {
                    Id        = 0,
                    Trackable = false
                }
            };

            var serializedMessage = JsonSerializer.Serialize(sendEmailMessage);
            var sendingBody       = Encoding.UTF8.GetBytes(serializedMessage);

            var Logger = new Logger <RabbitMQConnectionFactory>(new NLogLoggerFactory());

            var connectionFactory = new RabbitMQConnectionFactory(Logger);
            var connection        = connectionFactory.CreateConnection(
                configuration.MessageBrokerHost,
                configuration.MessageBrokerUsername,
                configuration.MessageBrokerPassword,
                configuration.MessageBrokerVirtualHost);
            var channel = connection.CreateModel();

            var properties = channel.CreateBasicProperties();

            properties.Persistent = true;

            channel.BasicPublish(configuration.EmailSendExchange, configuration.EmailSendKey, false, properties, sendingBody);
        }
        public void Connect_Success()
        {
            //Arrange
            var connectionFactory = new RabbitMQConnectionFactory(CONNECTION_STRING);

            //Act
            using var connection = connectionFactory.CreateConnection(nameof(IntegrationTests));

            //Assert
            Assert.NotNull(connection);
        }
        public void CreateConnection_InvalidExchange_ArgumentNullException(string exchange)
        {
            //Arrange
            var connectionString  = "amqp://localhost:1234/";
            var connectionFactory = new RabbitMQConnectionFactory(connectionString);

            //Act
            var action = new Action(() => connectionFactory.CreateConnection(exchange));

            //Assert
            Assert.Throws <ArgumentNullException>(nameof(exchange), action);
        }
    public void CreateConnection_ConnectionFactoryMock_AlwaysCreateNewConnection(int times)
    {
        var connectionFactoryMock = new Mock <IConnectionFactory>();
        var rabbitFactory         = new RabbitMQConnectionFactory <string>(connectionFactoryMock.Object);

        for (var i = 0; i < times; i++)
        {
            rabbitFactory.CreateConnection();
        }

        connectionFactoryMock.Verify(f => f.CreateConnection(), Times.Exactly(times));
    }
    public void FromConsumerConfig_NoQueueConfig_Throws()
    {
        var cfg = new RabbitMQConsumerOptions <string>
        {
            Host        = "host",
            VirtualHost = "vHost",
            User        = "******",
            Password    = "******",
            Queue       = null
        };

        Assert.Throws <ValidationException>(() => RabbitMQConnectionFactory <string> .From(cfg));
    }
Example #14
0
        // GET api/values
        public void Get()
        {
            RabbitMQConnectionFactory Instance = RabbitMQConnectionFactory.RabbitMQConnectionFactoryInstance;

            Instance.CreateFanoutExchange("SendMessages", true, false);

            System.Collections.IEnumerable quotes = FetchStockQuotes(new[] { "GOOG", "HD", "MCD" });
            foreach (string quote in quotes)
            {
                byte[] message     = Encoding.UTF8.GetBytes(quote);
                bool   isPublished = Instance.PublishMessage("SendMessages", "", false, null, message, 0);
            }
        }
Example #15
0
 public void Setup()
 {
     _factory = new RabbitMQConnectionFactory(
         RabbitMQProtocol.AMQP,
         "localhost",
         "/",
         5672,
         null,
         new ContainerBuilder().Build(),
         "brian",
         "development"
         );
 }
Example #16
0
        public void TestConnection()
        {
            var connectionDetail = new RabbitMQConnectionDetail()
            {
                HostName = "localhost", UserName = "******", Password = "******"
            };

            var rabbitMQConnectionFactory = new RabbitMQConnectionFactory(connectionDetail);

            _connection = rabbitMQConnectionFactory.CreateConnection();

            Assert.True(_connection.IsOpen);
        }
Example #17
0
        public void FromPublisherConfig_NullPublishingTarget_Throws()
        {
            var factory = new RabbitMQConnectionFactory();
            var cfg = new RabbitMQPublisherOptions<string>
            {
                Host = "host",
                User = "******",
                Password = "******",
                VirtualHost = "vHost",
                PublishingTarget = null
            };

            Assert.Throws<ArgumentException>(() => factory.From(cfg));
        }
Example #18
0
        public void FromConsumerConfig_NoQueueConfig_Throws()
        {
            var factory = new RabbitMQConnectionFactory();
            var cfg     = new RabbitMQConsumerConfig <string>
            {
                Host        = "host",
                VirtualHost = "vHost",
                User        = "******",
                Password    = "******",
                Queue       = null
            };

            Assert.Throws <ArgumentException>(() => factory.From(cfg));
        }
Example #19
0
    public static void AddRabbitMQWithConfig <T>(this IPublisherBuilder <T> builder, IConfiguration config) where T : notnull
    {
        builder.AddTransient <CloudEventFormatter, JsonEventFormatter>();
        builder.Configure <RabbitMQPublisherOptions <T> >(config);

        var rabbitMqPublisherOptions = config.Get <RabbitMQPublisherOptions <T> >();
        var connectionFactory        = RabbitMQConnectionFactory <T> .From(rabbitMqPublisherOptions);

        builder.AddPublisher(sp
                             => new RabbitMQMessagePublisher <T>(connectionFactory,
                                                                 MSOptions.Create(rabbitMqPublisherOptions),
                                                                 sp.GetRequiredService <IOptions <PublisherOptions> >(),
                                                                 sp.GetRequiredService <CloudEventFormatter>()));
    }
        public void CreateConnection_BrokerUnreachableException()
        {
            //Arrange
            var connectionMock            = new Mock <Rabbit.IConnection>(MockBehavior.Strict);
            var rabbitMqConnectionFactory = new Mock <Rabbit.IConnectionFactory>(MockBehavior.Strict);

            rabbitMqConnectionFactory.Setup((factory) => factory.CreateConnection()).Throws(new Rabbit.Exceptions.BrokerUnreachableException(null));
            var connectionFactory = new RabbitMQConnectionFactory(rabbitMqConnectionFactory.Object);

            //Act
            var action = new Action(() => connectionFactory.CreateConnection("test"));

            //Assert
            Assert.Throws <BrokerUnreachableException>(action);
        }
        public void CreateConnection_Succes()
        {
            //Arrange
            var connectionMock            = new Mock <Rabbit.IConnection>(MockBehavior.Strict);
            var rabbitMqConnectionFactory = new Mock <Rabbit.IConnectionFactory>(MockBehavior.Strict);

            rabbitMqConnectionFactory.Setup((factory) => factory.CreateConnection()).Returns(connectionMock.Object);
            var connectionFactory = new RabbitMQConnectionFactory(rabbitMqConnectionFactory.Object);

            //Act
            var connection = connectionFactory.CreateConnection("test");

            //Assert
            rabbitMqConnectionFactory.Verify((factory) => factory.CreateConnection(), Times.Once);
        }
    public void CurrentConnection_ConnectionFactoryMock_CreateConnectionOnlyOnce(int times)
    {
        var connectionMock        = Mock.Of <IConnection>();
        var connectionFactoryMock = new Mock <IConnectionFactory>();

        connectionFactoryMock
        .Setup(f => f.CreateConnection())
        .Returns(connectionMock);
        var rabbitFactory = new RabbitMQConnectionFactory <string>(connectionFactoryMock.Object);

        for (var i = 0; i < times; i++)
        {
            var _ = rabbitFactory.CurrentConnection;
        }

        connectionFactoryMock.Verify(f => f.CreateConnection(), Times.Once);
    }
Example #23
0
        public void FromPublisherConfig_CorrectConfig_ContainsAllValues()
        {
            const string host = "host";
            const string user = "******";
            const string password = "******";
            const string vHost = "vHost";
            const int port = 1000;
            var factory = new RabbitMQConnectionFactory();
            var cfg = GetPublisherConfig(host, user, password, vHost, "exchange", "test");
            cfg.Port = port;

            var connectionFactory = factory.From(cfg);

            Assert.Equal(user, connectionFactory.UserName);
            Assert.Equal(password, connectionFactory.Password);
            Assert.Equal(vHost, connectionFactory.VirtualHost);
        }
    public void CreateChannel_ConnectionFactoryMock_AlwaysCreateNewChannel(int times)
    {
        var connectionMock        = new Mock <IConnection>();
        var connectionFactoryMock = new Mock <IConnectionFactory>();

        connectionFactoryMock
        .Setup(f => f.CreateConnection())
        .Returns(connectionMock.Object);
        var rabbitFactory = new RabbitMQConnectionFactory <string>(connectionFactoryMock.Object);

        for (var i = 0; i < times; i++)
        {
            rabbitFactory.CreateModel();
        }

        connectionMock.Verify(c => c.CreateModel(), Times.Exactly(times));
    }
Example #25
0
        private void RabbitMQSubscription()
        {
            RabbitMQConnectionFactory rmqConn = RabbitMQConnectionFactory.RabbitMQConnectionFactoryInstance;

            rmqConn.CreateDirectExchange("Events", false, true);

            rmqConn.CreateQueue("EventsQueue", false, true, null);
            rmqConn.BindQueue("EventsQueue", "Events", "UserCreatedEvent");
            try
            {
                var consumer = rmqConn.ConsumerEventHandlers();
                consumer.Received += Consumer_Received;
                rmqConn.Consume("EventsQueue", true, consumer);
            }
            catch (Exception ex)
            {
            }
        }
Example #26
0
    public static void AddRabbitMQWithConfig <T>(this IConsumerBuilder <T> builder, IConfiguration config)
        where T : notnull
    {
        builder.AddTransient <CloudEventFormatter, JsonEventFormatter>();
        var consumerOptions = new RabbitMQConsumerOptions <T>();

        config.Bind(consumerOptions);
        var connectionFactory = RabbitMQConnectionFactory <T> .From(consumerOptions);

        builder.AddConsumer(sp => new RabbitMQMessageConsumer <T>(
                                sp.GetRequiredService <ILogger <RabbitMQMessageConsumer <T> > >(),
                                connectionFactory,
                                MSOptions.Create(consumerOptions),
                                sp.GetRequiredService <IHostApplicationLifetime>(),
                                sp.GetRequiredService <IApplicationNameService>()));
        builder.AddSingleton <IQueueMonitor>(sp =>
                                             new RabbitMQQueueMonitor <T>(sp.GetRequiredService <ILogger <RabbitMQQueueMonitor <T> > >(),
                                                                          MSOptions.Create(consumerOptions), connectionFactory));
    }
Example #27
0
        public void StoreEvents(ICommand createUserCmd, object streamId, IEnumerable <object> events)
        {
            if (createUserCmd is CreateUserCommand)
            {
                StoreUsers(createUserCmd);
            }
            else if (createUserCmd is UpdateUserCommand)
            {
            }
            string str = JsonConvert.SerializeObject(events.First <object>());

            byte[] message = Encoding.UTF8.GetBytes(str);

            RabbitMQConnectionFactory rmqConn = RabbitMQConnectionFactory.RabbitMQConnectionFactoryInstance;

            rmqConn.CreateDirectExchange("Events", false, true);
            rmqConn.PublishMessage("Events", "UserCreatedEvent", false, null, message, 0);
            // _bus.Publish(events);
        }
Example #28
0
        private static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.Console(outputTemplate:
                                          "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}",
                                          theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            // Appsettings is renamed because of an issue where the project loaded another appsettings.json
            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettingsnotificationsystem.json", true, true)
                                           .AddJsonFile($"appsettingsnotificationsystem.{environmentName}.json",
                                                        true,
                                                        true)
                                           .AddEnvironmentVariables()
                                           .Build();
            Config config = configuration.GetSection("App")
                            .Get <Config>();

            IRabbitMQConnectionFactory connectionFactory =
                new RabbitMQConnectionFactory(config.RabbitMQ.Hostname,
                                              config.RabbitMQ.Username,
                                              config.RabbitMQ.Password);

            RabbitMQSubscriber subscriber = new RabbitMQSubscriber(connectionFactory);
            IModel             channel    = subscriber.SubscribeToSubject("EMAIL");

            RabbitMQListener listener = new RabbitMQListener(channel);

            // inject your notification service here
            ISendGridClient       sendGridClient      = new SendGridClient(config.SendGrid.ApiKey);
            ICallbackService      notificationService = new EmailSender(sendGridClient, config.SendGrid.EmailFrom, config.SendGrid.SandboxMode);
            EventingBasicConsumer consumer            = listener.CreateConsumer(notificationService);

            listener.StartConsumer(consumer, "EMAIL");
            Console.ReadLine();
        }
Example #29
0
        private void RabbitMQ()
        {
            RabbitMQConnectionFactory rmq = RabbitMQConnectionFactory.RabbitMQConnectionFactoryInstance;

            rmq.CreateFanoutExchange("SendMessages", false, true);
            rmq.CreateQueue("A", false, true);
            rmq.BindQueue("A", "SendMessages", "");


            try
            {
                var consumer = rmq.ConsumerEventHandlers();
                consumer.Received += Consumer_Received;
                rmq.Consume("A", true, consumer);
            }
            catch (Exception ex)
            {
            }
        }
Example #30
0
        private bool SendCredentialsToEmail(string login, string password, string mailAddress, string fullName, IUnitOfWork unitOfWork)
        {
            var instanceId = Convert.ToInt32(unitOfWork.Session
                                             .CreateSQLQuery("SELECT GET_CURRENT_DATABASE_ID()")
                                             .List <object>()
                                             .FirstOrDefault());

            var configuration = unitOfWork.GetAll <InstanceMailingConfiguration>().FirstOrDefault();

            string messageText =
                $"Логин: { login }\n" +
                $"Пароль: { password }";

            var sendEmailMessage = new SendEmailMessage()
            {
                From = new EmailContact
                {
                    Name  = _emailParametersProvider.DocumentEmailSenderName,
                    Email = _emailParametersProvider.DocumentEmailSenderAddress
                },

                To = new List <EmailContact>
                {
                    new EmailContact
                    {
                        Name  = fullName,
                        Email = mailAddress
                    }
                },

                Subject = "Учетные данные для входа в программу Доставка Воды",

                TextPart = messageText,
                HTMLPart = messageText,
                Payload  = new EmailPayload
                {
                    Id         = 0,
                    Trackable  = false,
                    InstanceId = instanceId
                }
            };

            try
            {
                var serializedMessage = JsonSerializer.Serialize(sendEmailMessage);
                var sendingBody       = Encoding.UTF8.GetBytes(serializedMessage);

                var Logger = new Logger <RabbitMQConnectionFactory>(new NLogLoggerFactory());

                var connectionFactory = new RabbitMQConnectionFactory(Logger);
                var connection        = connectionFactory.CreateConnection(configuration.MessageBrokerHost, configuration.MessageBrokerUsername, configuration.MessageBrokerPassword, configuration.MessageBrokerVirtualHost);
                var channel           = connection.CreateModel();

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(configuration.EmailSendExchange, configuration.EmailSendKey, false, properties, sendingBody);

                return(true);
            }
            catch (Exception e)
            {
                _logger.Error(e, e.Message);
                return(false);
            }
        }