コード例 #1
0
 /// <summary>
 /// Открывает соединение с RabbitMQ
 /// </summary>
 public void OpenRabbitMQConnection()
 {
     Connection                   = RabbitMQConnectionFactory.CreateConnection();
     RabbitChannel                = Connection.CreateModel();
     _rabbitProperties            = RabbitChannel.CreateBasicProperties();
     _rabbitProperties.Persistent = true;
 }
コード例 #2
0
        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);
        }
コード例 #3
0
 /// <summary>
 /// Открывает соединение с RabbitMQ
 /// </summary>
 private void OpenRabbitMQConnection()
 {
     Connection        = RabbitMQConnectionFactory.CreateConnection();
     RabbitChannel     = Connection.CreateModel();
     _rabbitProperties = RabbitChannel.CreateBasicProperties();
     _rabbitProperties.SetPersistent(true);
 }
コード例 #4
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);
        }
コード例 #5
0
        public void Connect_Success()
        {
            //Arrange
            var connectionFactory = new RabbitMQConnectionFactory(CONNECTION_STRING);

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

            //Assert
            Assert.NotNull(connection);
        }
コード例 #6
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 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);
        }
コード例 #8
0
    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));
    }
コード例 #9
0
ファイル: RabbitMQTest.cs プロジェクト: seansheraton/playpen
        public void TestConnection()
        {
            var connectionDetail = new RabbitMQConnectionDetail()
            {
                HostName = "localhost", UserName = "******", Password = "******"
            };

            var rabbitMQConnectionFactory = new RabbitMQConnectionFactory(connectionDetail);

            _connection = rabbitMQConnectionFactory.CreateConnection();

            Assert.True(_connection.IsOpen);
        }
        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 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);
        }
コード例 #12
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);
            }
        }