<file_sep># rabbitmq-demo5-topics
Demo 5 Topics
- Receiving messages based on a pattern (topics) 
<file_sep>﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;

namespace ReceiveLogs
{
    class ReceiveLogs
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine("Write the log types you want to receive:");
            Console.WriteLine("The options are: system.info, application.warning and system.error");
            Console.WriteLine("Try combination with * and # to bind to desired topic");
            Console.WriteLine("Ex.: '*.info' , 'system.*'");



            var input = Console.ReadLine();

            var severities = input.Split(' ');

            var factory = new ConnectionFactory()
            {
                HostName = "192.168.15.33",
                UserName = "renatocolaco",
                Password = "<PASSWORD>"
            };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                // This tells RabbitMQ not to give more than one message to a worker at a time
                // prefetchCount: 1
                channel.ExchangeDeclare(exchange: "topic_logs", type: "topic");

                var queueName = channel.QueueDeclare().QueueName;

                foreach (var sev in severities)
                {
                    channel.QueueBind(queue: queueName, exchange: "topic_logs", routingKey: sev);
                }
                
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) => {

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);

                    Console.WriteLine(" [x] message received {0}", message);
                    Thread.Sleep(4000);
                    Console.WriteLine(" [#] Done");
                };

                channel.BasicConsume(
                    queue: queueName,
                    autoAck: true,
                    consumer: consumer
                    );

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }
    }
}
<file_sep>﻿using RabbitMQ.Client;
using System;
using System.Text;
using System.Timers;
using System.Security.Cryptography;

namespace EmitLog
{
    class EmitLog
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            SetTimer();

            Console.ReadKey();
        }

        private static void SetTimer()
        {
            // Create a timer with a two second interval.
            var messageTimer = new Timer(2000);
            // Hook up the Elapsed event for the timer. 
            messageTimer.Elapsed += OnTimedEvent;
            messageTimer.AutoReset = true;
            messageTimer.Enabled = true;
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "192.168.15.33",
                UserName = "renatocolaco",
                Password = "<PASSWORD>"
            };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "topic_logs", type: "topic");
                
                var message = GetMessage();
                string severity = GetSeverity();

                var body = Encoding.UTF8.GetBytes($"[{severity}] {message}");
                                
                channel.BasicPublish(exchange: "topic_logs",
                                     routingKey: severity,
                                     basicProperties: null,
                                     body: body);
            }

            Console.WriteLine("A new message published to the queue at {0:HH:mm:ss.fff}",
                              e.SignalTime);
        }

        /// <summary>
        /// Gets a random severity 
        /// </summary>
        /// <returns></returns>
        private static string GetSeverity()
        {
            var severityArr = new string[] {
                "system.info",
                "system.warning",
                "system.error",
                "application.info",
                "application.warning",
                "application.error"
            };

            using (var randomNumberGenerator = RandomNumberGenerator.Create())
            {
                var randomNumber = new byte[1];
                randomNumberGenerator.GetBytes(randomNumber);
                var rest = randomNumber[0] % severityArr.Length;
                return severityArr[rest];
            }
        }

        private static string GetMessage()
        {
            return $"Hello World! {DateTime.Now:HH:mm:ss}";
        }
    }
}
