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)); }
/// <summary> /// Открывает соединение с RabbitMQ /// </summary> private void OpenRabbitMQConnection() { Connection = RabbitMQConnectionFactory.CreateConnection(); RabbitChannel = Connection.CreateModel(); _rabbitProperties = RabbitChannel.CreateBasicProperties(); _rabbitProperties.SetPersistent(true); }
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)); }
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); }
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); }
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); }
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); }
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)); }
// 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); } }
public void Setup() { _factory = new RabbitMQConnectionFactory( RabbitMQProtocol.AMQP, "localhost", "/", 5672, null, new ContainerBuilder().Build(), "brian", "development" ); }
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 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)); }
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)); }
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); }
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)); }
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) { } }
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)); }
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); }
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(); }
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) { } }
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); } }