public override IMessageQueue GetResponseQueue()
        {
            if (!(Connection.Pattern == MessagePattern.RequestResponse && Connection.Direction == Direction.Outbound))
            {
                throw new InvalidOperationException("Cannot get a response queue except for outbound request-response");
            }

            if (ResponseQueue != null)
            {
                return(ResponseQueue);
            }

            // make unique based on timestamp and guid
            var address    = $".\\private$\\{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}:{Guid.NewGuid().ToString().Trim('{','}')}";
            var connection = new MessageQueueConnection {
                Address = address, Pattern = MessagePattern.RequestResponse, Direction = Direction.Inbound
            };

            ResponseQueue = QueueFactory.Create(connection);
            return(ResponseQueue);
        }
Beispiel #2
0
        private static void LoadMessageQueueConnections(WJOPConfiguration config)
        {
            AppContext._messageQueueConnections = new List <MessageQueueConnection>();
            WJOPMessageQueueElement item = null;

            for (int i = 0; i < config.MessageQueueConnections.Count; i++)
            {
                item = config.MessageQueueConnections[i];
                MessageQueueConnection messageQueueConnection = new MessageQueueConnection()
                {
                    ConnectionName     = item.ConnectionName,
                    HostUrl            = item.HostUrl,
                    Space              = item.Space,
                    Password           = item.Password,
                    UserName           = item.UserName,
                    Prefetchcount      = item.Prefetchcount,
                    RequestedHeartbeat = item.RequestedHeartbeat,
                    Timeout            = item.Timeout
                };
                AppContext._messageQueueConnections.Add(messageQueueConnection);
            }
        }
        public void Listen(CancellationToken cancellationToken, int listenerId)
        {
            _listenerId = listenerId;
            Connection  = MessageQueueConnection.GetConnectionFactory().CreateConnection();
            using (var channel = Connection.CreateModel())
            {
                Consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(RabbitMQConfiguration.QueueName, true, Consumer);
                Log.Info(x => x("(Id={0}) Waiting for messages...", _listenerId));

                while (true)
                {
                    var message = new DispatchTrigger();
                    try
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var eventArgs = (BasicDeliverEventArgs)Consumer.Queue.Dequeue();
                        var body      = eventArgs.Body;
                        message = JsonConvert.DeserializeObject <DispatchTrigger>(Encoding.UTF8.GetString(body));
                        Log.Debug(x => x("Message queue listener received {0}", message));
                        if (IntegrationJobTypes != null && !IntegrationJobTypes.Any())
                        {
                            continue;
                        }
                        var type           = IntegrationJobTypes.FirstOrDefault(t => t.FullName.Equals(message.JobType));
                        var integrationJob = UnityContainer.Resolve(type) as IIntegrationJob;
                        if (integrationJob != null)
                        {
                            if (integrationJob is IParameterizedJob)
                            {
                                var parameterizedJob = integrationJob as IParameterizedJob;
                                parameterizedJob.Parameters = message.Parameters;
                                Log.Info(x => x("Running job: {0} with parameters {1}", integrationJob, message.Parameters));
                                parameterizedJob.Run();
                            }
                            else
                            {
                                Log.Info(x => x("Running job: {0}", integrationJob));
                                integrationJob.Run();
                            }
                            Log.Info(x => x("Integration job ran successfully: {0}", integrationJob));
                        }
                    }
                    catch (OperationCanceledException exception)
                    {
                        Log.Info(x => x("Message queue listener (id: {0}), listening on queue \"{1}\", has gracefully shutdown.",
                                        _listenerId,
                                        RabbitMQConfiguration.QueueName), exception);
                        return;
                    }
                    catch (IntegrationJobRunFailureException exception)
                    {
                        Log.Error(x => x("Integration job did not run successfully ({0}).", message.JobType), exception);
                    }
                    catch (EndOfStreamException exception)
                    {
                        Log.Debug(x => x("The message queue ({0}) has closed.", RabbitMQConfiguration.QueueName), exception);
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Issue receiving/decoding dispatch message or running job.", exception);
                    }
                }
            }
        }
        public void Startup()
        {
            //
            //	get configuration information
            //

            MessageQueueAppConfig messageQueueAppConfig = new MessageQueueAppConfig();
            ConnectionStrings     connectionStrings     = new ConnectionStrings();

            var basePath = PlatformServices.Default.Application.ApplicationBasePath;

            if (basePath.ToLower().Contains("salesordermanagementqa"))
            {
                CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings appSettings = new CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings();

                string readContents;
                using (StreamReader streamReader = new StreamReader(basePath + @"\AppSettings.QA.json", Encoding.UTF8))
                {
                    readContents = streamReader.ReadToEnd();
                }

                appSettings = CodeProject.Shared.Common.Utilities.SerializationFunction <CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings> .ReturnObjectFromString(readContents);

                messageQueueAppConfig.MessageQueueHostName    = appSettings.MessageQueueAppConfig.MessageQueueHostName;
                messageQueueAppConfig.MessageQueueUserName    = appSettings.MessageQueueAppConfig.MessageQueueUserName;
                messageQueueAppConfig.MessageQueuePassword    = appSettings.MessageQueueAppConfig.MessageQueuePassword;
                messageQueueAppConfig.MessageQueueEnvironment = appSettings.MessageQueueAppConfig.MessageQueueEnvironment;
                messageQueueAppConfig.ExchangeName            = appSettings.MessageQueueAppConfig.ExchangeName;
                messageQueueAppConfig.RoutingKey            = appSettings.MessageQueueAppConfig.RoutingKey;
                messageQueueAppConfig.InboundMessageQueue   = appSettings.MessageQueueAppConfig.InboundMessageQueue;
                messageQueueAppConfig.OutboundMessageQueues = appSettings.MessageQueueAppConfig.OutboundMessageQueues;
                messageQueueAppConfig.LoggingExchangeName   = appSettings.MessageQueueAppConfig.LoggingExchangeName;
                messageQueueAppConfig.LoggingMessageQueue   = appSettings.MessageQueueAppConfig.LoggingMessageQueue;
                messageQueueAppConfig.OriginatingQueueName  = appSettings.MessageQueueAppConfig.OriginatingQueueName;
                messageQueueAppConfig.SendToLoggingQueue    = appSettings.MessageQueueAppConfig.SendToLoggingQueue;
                messageQueueAppConfig.AcknowledgementMessageExchangeSuffix = appSettings.MessageQueueAppConfig.AcknowledgementMessageExchangeSuffix;
                messageQueueAppConfig.AcknowledgementMessageQueueSuffix    = appSettings.MessageQueueAppConfig.AcknowledgementMessageQueueSuffix;
                messageQueueAppConfig.TriggerExchangeName       = appSettings.MessageQueueAppConfig.TriggerExchangeName;
                messageQueueAppConfig.TriggerQueueName          = appSettings.MessageQueueAppConfig.TriggerQueueName;
                messageQueueAppConfig.QueueImmediately          = appSettings.MessageQueueAppConfig.QueueImmediately;
                messageQueueAppConfig.InboundSemaphoreKey       = appSettings.MessageQueueAppConfig.InboundSemaphoreKey;
                messageQueueAppConfig.OutboundSemaphoreKey      = appSettings.MessageQueueAppConfig.OutboundSemaphoreKey;
                messageQueueAppConfig.ProcessingIntervalSeconds = appSettings.MessageQueueAppConfig.ProcessingIntervalSeconds;
                messageQueueAppConfig.SendingIntervalSeconds    = appSettings.MessageQueueAppConfig.SendingIntervalSeconds;
                messageQueueAppConfig.ReceivingIntervalSeconds  = appSettings.MessageQueueAppConfig.ReceivingIntervalSeconds;
                messageQueueAppConfig.SignalRHubUrl             = appSettings.MessageQueueAppConfig.SignalRHubUrl;
                messageQueueAppConfig.RunAsService = appSettings.MessageQueueAppConfig.RunAsService;

                connectionStrings.PrimaryDatabaseConnectionString = appSettings.ConnectionStrings.PrimaryDatabaseConnectionString;

                using (var sw = File.AppendText(Path))
                {
                    sw.WriteLine("HostName=" + messageQueueAppConfig.MessageQueueHostName + "*");
                }
            }
            else
            {
                string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                string jsonFile    = $"AppSettings.{environment}.json";

                var configBuilder = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile(jsonFile, optional: true, reloadOnChange: true);

                IConfigurationRoot configuration = configBuilder.Build();

                configuration.GetSection("MessageQueueAppConfig").Bind(messageQueueAppConfig);
                configuration.GetSection("ConnectionStrings").Bind(connectionStrings);
            }

            //
            //	set up sending queue
            //

            IMessageQueueConnection sendingQueueConnection = new MessageQueueConnection(messageQueueAppConfig);

            sendingQueueConnection.CreateConnection();

            List <IMessageQueueConfiguration> messageQueueConfigurations = new List <IMessageQueueConfiguration>();

            IMessageQueueConfiguration salesOrderSubmittedConfiguration = new MessageQueueConfiguration(MessageQueueExchanges.SalesOrderSubmitted, messageQueueAppConfig, sendingQueueConnection);

            salesOrderSubmittedConfiguration.AddQueue(MessageQueueEndpoints.InventoryQueue);
            salesOrderSubmittedConfiguration.AddQueue(MessageQueueEndpoints.LoggingQueue);

            salesOrderSubmittedConfiguration.InitializeOutboundMessageQueueing();
            messageQueueConfigurations.Add(salesOrderSubmittedConfiguration);

            ISalesOrderManagementDataService salesOrderManagementDataService = new SalesOrderManagementDataService();
            IMessageQueueProcessing          messageProcessing = new MessageProcessing(salesOrderManagementDataService);

            _sendSalesOrderManagementMessages =
                new SendMessages(sendingQueueConnection, messageProcessing, messageQueueAppConfig,
                                 connectionStrings, messageQueueConfigurations, MessageQueueEndpoints.SalesOrderQueue);


            //
            //	set up receiving queue
            //

            IMessageQueueConnection receivingConnection = new MessageQueueConnection(messageQueueAppConfig);

            receivingConnection.CreateConnection();

            List <IMessageQueueConfiguration> inboundMessageQueueConfigurations = new List <IMessageQueueConfiguration>();
            IMessageQueueConfiguration        inboundConfiguration = new MessageQueueConfiguration(messageQueueAppConfig, receivingConnection);

            inboundMessageQueueConfigurations.Add(inboundConfiguration);

            inboundConfiguration.InitializeInboundMessageQueueing(MessageQueueEndpoints.SalesOrderQueue);
            inboundConfiguration.InitializeLoggingExchange(MessageQueueExchanges.Logging, MessageQueueEndpoints.LoggingQueue);
            ISalesOrderManagementDataService inboundSalesOrderManagementDataService = new SalesOrderManagementDataService();
            IMessageQueueProcessing          inboundMessageProcessing = new MessageProcessing(inboundSalesOrderManagementDataService);

            _receiveSalesOrderManagementMessages = new ReceiveMessages(receivingConnection, inboundMessageProcessing, messageQueueAppConfig, connectionStrings, inboundMessageQueueConfigurations);

            //
            //	Set Up Message Processing
            //

            ISalesOrderManagementDataService salesOrderManagementProcessingDataService = new SalesOrderManagementDataService();
            IMessageQueueProcessing          messageProcessor = new MessageProcessing(salesOrderManagementProcessingDataService);

            _processMessages = new ProcessMessages(messageProcessor, messageQueueAppConfig, connectionStrings);

            var builder = new HostBuilder().ConfigureAppConfiguration((hostingContext, config) =>
            {
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => _sendSalesOrderManagementMessages);
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => _processMessages);
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => _receiveSalesOrderManagementMessages);
            });
        }
        public static async Task Main(string[] args)
        {
            //
            //	get configuration information
            //
            MessageQueueAppConfig messageQueueAppConfig = new MessageQueueAppConfig();
            ConnectionStrings     connectionStrings     = new ConnectionStrings();

            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            string jsonFile    = $"appsettings.{environment}.json";

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile(jsonFile, optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = configBuilder.Build();

            configuration.GetSection("MessageQueueAppConfig").Bind(messageQueueAppConfig);
            configuration.GetSection("ConnectionStrings").Bind(connectionStrings);
            //
            //	set up sending queue
            //
            IMessageQueueConnection sendingQueueConnection = new MessageQueueConnection(messageQueueAppConfig);

            sendingQueueConnection.CreateConnection();

            List <IMessageQueueConfiguration> messageQueueConfigurations = new List <IMessageQueueConfiguration>();
            //
            //	Inventory Received Transactions
            //
            IMessageQueueConfiguration inventoryReceivedConfiguration = new MessageQueueConfiguration(MessageQueueExchanges.InventoryReceived, messageQueueAppConfig, sendingQueueConnection);

            inventoryReceivedConfiguration.AddQueue(MessageQueueEndpoints.SalesOrderQueue);
            inventoryReceivedConfiguration.AddQueue(MessageQueueEndpoints.PurchaseOrderQueue);
            inventoryReceivedConfiguration.AddQueue(MessageQueueEndpoints.LoggingQueue);

            inventoryReceivedConfiguration.InitializeOutboundMessageQueueing();
            messageQueueConfigurations.Add(inventoryReceivedConfiguration);
            //
            //	Product Creation and Updates
            //
            IMessageQueueConfiguration productUpdatedConfiguration = new MessageQueueConfiguration(MessageQueueExchanges.ProductUpdated, messageQueueAppConfig, sendingQueueConnection);

            productUpdatedConfiguration.AddQueue(MessageQueueEndpoints.SalesOrderQueue);
            productUpdatedConfiguration.AddQueue(MessageQueueEndpoints.PurchaseOrderQueue);
            productUpdatedConfiguration.AddQueue(MessageQueueEndpoints.LoggingQueue);

            productUpdatedConfiguration.InitializeOutboundMessageQueueing();
            messageQueueConfigurations.Add(productUpdatedConfiguration);
            //
            //	Inventory Shipped Transactions
            //
            IMessageQueueConfiguration inventoryShippedConfiguration = new MessageQueueConfiguration(MessageQueueExchanges.InventoryShipped, messageQueueAppConfig, sendingQueueConnection);

            inventoryShippedConfiguration.AddQueue(MessageQueueEndpoints.SalesOrderQueue);
            inventoryShippedConfiguration.AddQueue(MessageQueueEndpoints.LoggingQueue);

            inventoryShippedConfiguration.InitializeOutboundMessageQueueing();
            messageQueueConfigurations.Add(inventoryShippedConfiguration);

            //
            //	initialize Sending Messages
            //
            IInventoryManagementDataService inventoryManagementDataService = new InventoryManagementDataService();
            IMessageQueueProcessing         messageProcessing = new MessageProcessing(inventoryManagementDataService);

            IHostedService sendInventoryManagementMessages = new SendMessages(sendingQueueConnection, messageProcessing,
                                                                              messageQueueAppConfig, connectionStrings, messageQueueConfigurations, MessageQueueEndpoints.InventoryQueue);
            //
            //	set up receiving queue
            //
            IMessageQueueConnection receivingConnection = new MessageQueueConnection(messageQueueAppConfig);

            receivingConnection.CreateConnection();

            List <IMessageQueueConfiguration> inboundMessageQueueConfigurations = new List <IMessageQueueConfiguration>();
            IMessageQueueConfiguration        inboundConfiguration = new MessageQueueConfiguration(messageQueueAppConfig, receivingConnection);

            inboundMessageQueueConfigurations.Add(inboundConfiguration);

            inboundConfiguration.InitializeInboundMessageQueueing(MessageQueueEndpoints.InventoryQueue);
            inboundConfiguration.InitializeLoggingExchange(MessageQueueExchanges.Logging, MessageQueueEndpoints.LoggingQueue);
            IInventoryManagementDataService inboundInventoryManagementDataService = new InventoryManagementDataService();
            IMessageQueueProcessing         inboundMessageProcessing = new MessageProcessing(inboundInventoryManagementDataService);

            IHostedService receiveInventoryManagementMessages = new ReceiveMessages(receivingConnection, inboundMessageProcessing, messageQueueAppConfig, connectionStrings, inboundMessageQueueConfigurations);
            //
            //	Set Up Message Processing
            //
            IInventoryManagementDataService inventoryManagementProcessingDataService = new InventoryManagementDataService();
            IMessageQueueProcessing         messageProcessor = new MessageProcessing(inventoryManagementProcessingDataService);
            ProcessMessages processMessages = new ProcessMessages(messageProcessor, messageQueueAppConfig, connectionStrings);

            var builder = new HostBuilder().ConfigureAppConfiguration((hostingContext, config) => {})
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => processMessages);
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => sendInventoryManagementMessages);
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IHostedService>(provider => receiveInventoryManagementMessages);
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
            });

            await builder.RunConsoleAsync();
        }