/// <summary>
        /// Returns all the keys available in the class.
        /// </summary>
        public static IEnumerable <string> GetAllKeys()
        {
            #region Return
            return(MessageQueueCommonItems.GetAllStringConstants(typeof(ZeroMqConfigurationKeys)));

            #endregion
        }
Ejemplo n.º 2
0
        public void StartReceivingRequest()
        {
            try
            {
                lock (poller)
                {
                    if (!isReceivingMessages)
                    {
                        poller.Add(socket);

                        // Updating flag.
                        isReceivingMessages = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToStartReceivingRequest,
                          message: ErrorMessages.FailedToStartReceivingRequest,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private void ReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            try
            {
                // Receiving client message.
                var clientRequest = e.Socket.ReceiveMultipartMessage();

                // Parsing client message.
                var clientAddress     = clientRequest[0];
                var clientRequestData = MessageQueueCommonItems.DeserializeFromJson <TRequest>(clientRequest[2].ConvertToString());

                // Calling handler.
                OnRequestReady?.Invoke(new ZmqRequestMessage <TRequest, TResponse>(clientAddress, e.Socket, clientRequestData, ref logger));
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveRequestMessage,
                    message: ErrorMessages.FailedToReceiveRequestMessage,
                    innerException: ex,
                    queueContext: CommonItems.ZeroMqName,
                    address: zmqConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 4
0
        public void SendRequest(TRequest message)
        {
            #region Sending Message
            try
            {
                // Preparing message.
                var messageToServer = new NetMQMessage();
                messageToServer.AppendEmptyFrame();
                messageToServer.Append(MessageQueueCommonItems.SerializeToJson(message));

                // Sending message.
                socket.SendMultipartMessage(messageToServer);
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendMessage,
                          message: ErrorMessages.FailedToSendMessage,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration.Address,
                          logger: logger);
            }
            #endregion
        }
Ejemplo n.º 5
0
        public async Task SendMessageAsync(TMessage message)
        {
            try
            {
                #region Sending Message
                await Task.Run(() => SendMessage(message));

                #endregion
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendMessage,
                          message: ErrorMessages.FailedToSendMessage,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration.Address,
                          logger: logger);
            }
        }
        public override void Response(TResponse response)
        {
            try
            {
                #region Sending Response
                // Preparing response.
                var messageToClient = new NetMQMessage();
                messageToClient.Append(clientAddress);
                messageToClient.AppendEmptyFrame();
                messageToClient.Append(MessageQueueCommonItems.SerializeToJson(response));

                // Sending response.
                responseChannel.SendMultipartMessage(messageToClient);
                #endregion
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Error(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendResponseMessage,
                          message: ErrorMessages.FailedToSendResponseMessage,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          logger: logger);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private void ResponseReady(object sender, NetMQSocketEventArgs e)
        {
            try
            {
                // Receiving message.
                // Server will send empty frame followed by actual data frame so we need to skip the first frame.
                var receivedMessage = e.Socket.ReceiveMultipartStrings();

                if (receivedMessage.Count > 1)
                {
                    // Converting from Json.
                    var convertedMessage = MessageQueueCommonItems.DeserializeFromJson <TResponse>(receivedMessage[1]);

                    // Calling handler.
                    OnResponseReady?.Invoke(convertedMessage);
                }
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveResponseMessage,
                    message: ErrorMessages.FailedToReceiveResponseMessage,
                    innerException: ex,
                    queueContext: CommonItems.ZeroMqName,
                    address: zmqConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 8
0
        public void SendMessage(TMessage message)
        {
            try
            {
                #region Sending Message
                // We need to lock as the sockets are not multi-threaded in ZeroMq.
                lock (lockForQueueOperation)
                {
                    socket.SendFrame(MessageQueueCommonItems.SerializeToJson(message));
                }
                #endregion
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendMessage,
                          message: ErrorMessages.FailedToSendMessage,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Helper method to create the exchange.
        /// </summary>
        protected virtual void CreateExchange(AmqpExchangeType exchangeType)
        {
            #region Validation
            CheckIfQueueHasInitialized();
            #endregion

            #region Creating Exchange
            try
            {
                model.ExchangeDeclare(rabbitMqConfiguration.ExchangeName, exchangeType.ToString(), rabbitMqConfiguration.DurableExchange);
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToCreateExchange,
                          message: ErrorMessages.FailedToCreateExchange,
                          innerException: ex,
                          queueContext: CommonItems.RabbitMqName,
                          address: rabbitMqConfiguration.Address,
                          context: new Dictionary <string, string>
                {
                    [CommonContextKeys.ExchangeName] = rabbitMqConfiguration.ExchangeName
                },
                          logger: logger);
            }
            #endregion
        }
Ejemplo n.º 10
0
        public bool HasMessage()
        {
            try
            {
                // Creating new receiver just to avoid closed connection issue.
                var messageReceiverToPeek = queueClient.MessagingFactory.CreateMessageReceiver(sbConfiguration.QueueName, ReceiveMode.PeekLock);

                // Peeking
                var result = messageReceiverToPeek.Peek() != null;

                // Closing connection.
                messageReceiverToPeek.Close();

                return(result);
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToCheckQueueHasMessage,
                          message: ErrorMessages.FailedToCheckQueueHasMessage,
                          innerException: ex,
                          queueContext: CommonItems.ServiceBusName,
                          queueName: sbConfiguration.QueueName,
                          address: sbConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 11
0
        public ZmqInboundRaR(Dictionary <string, string> configuration, IQueueLogger loggerObject)
        {
            try
            {
                #region Initialization
                base.Initialize(configuration, ZeroMqSocketType.Router, true, loggerObject);

                // Setting fields.
                Address = zmqConfiguration.Address;

                // Binding on receive event.
                base.socket.ReceiveReady += ReceiveReady;

                // Initializing poller.
                poller = new NetMQPoller();
                poller.RunAsync();
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration?.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Method to create the queue.
        /// </summary>
        protected virtual QueueDeclareOk CreateQueue()
        {
            #region Validation
            CheckIfQueueHasInitialized();
            #endregion

            #region Initialization
            QueueDeclareOk queueDeclareOk;
            #endregion

            #region Creating Queue
            try
            {
                queueDeclareOk = model.QueueDeclare(rabbitMqConfiguration.QueueName, rabbitMqConfiguration.DurableQueue, false, false, null);
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToCreateMessageQueue,
                          message: ErrorMessages.FailedToCreateMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.RabbitMqName,
                          queueName: rabbitMqConfiguration.QueueName,
                          address: rabbitMqConfiguration.Address,
                          logger: logger);
            }
            #endregion

            #region Return
            return(queueDeclareOk);

            #endregion
        }
Ejemplo n.º 13
0
        public void StopReceivingMessage()
        {
            try
            {
                lock (consumer)
                {
                    if (isReceivingMessages)
                    {
                        model.BasicCancel(consumer.ConsumerTag);

                        // Updating flag.
                        isReceivingMessages = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToStopReceivingMessage,
                    message: ErrorMessages.FailedToStopReceivingMessage,
                    innerException: ex,
                    queueContext: CommonItems.RabbitMqName,
                    queueName: rabbitMqConfiguration.QueueName,
                    address: rabbitMqConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 14
0
        public void StartReceivingMessage()
        {
            try
            {
                lock (consumer)
                {
                    if (!isReceivingMessages)
                    {
                        // Binding consumer with queue to start receiving messages.
                        model.BasicConsume(rabbitMqConfiguration.QueueName, !rabbitMqConfiguration.Acknowledgment, consumer);

                        // Updating flag.
                        isReceivingMessages = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToStartReceivingMessage,
                          message: ErrorMessages.FailedToStartReceivingMessage,
                          innerException: ex,
                          queueContext: CommonItems.RabbitMqName,
                          queueName: rabbitMqConfiguration.QueueName,
                          address: rabbitMqConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 15
0
        public void StopReceivingMessage()
        {
            try
            {
                lock (poller)
                {
                    if (isReceivingMessages)
                    {
                        poller.Remove(socket);

                        // Updating flag.
                        isReceivingMessages = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToStopReceivingMessage,
                    message: ErrorMessages.FailedToStopReceivingMessage,
                    innerException: ex,
                    queueContext: CommonItems.ZeroMqName,
                    address: zmqConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 16
0
        public ZmqOutboundRaR(Dictionary <string, string> configuration, IQueueLogger loggerObject)
        {
            try
            {
                #region Initialization
                base.Initialize(configuration, ZeroMqSocketType.Dealer, false, loggerObject);

                // Setting fields.
                Address = zmqConfiguration.Address;

                // Need to set some unique identifier for connection identity (ZeroMq requirement).
                socketIdentity          = Guid.NewGuid().ToString("N");
                socket.Options.Identity = Encoding.Unicode.GetBytes(socketIdentity);

                // Binding on receive event.
                socket.ReceiveReady += ResponseReady;

                // Initializing poller and starting it.
                poller = new NetMQPoller {
                    socket
                };
                poller.RunAsync();
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration?.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 17
0
        public async Task SendMessageAsync(TMessage message)
        {
            try
            {
                #region Sending Message
                CheckConnection();

                await queueClient.SendAsync(new BrokeredMessage(new MemoryStream(MessageQueueCommonItems.SerializeToJsonBytes(message))));

                #endregion
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendMessage,
                          message: ErrorMessages.FailedToSendMessage,
                          innerException: ex,
                          queueContext: CommonItems.ServiceBusName,
                          queueName: sbConfiguration.QueueName,
                          address: sbConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 18
0
        public SbInboundFaF(Dictionary <string, string> configuration, IQueueLogger loggerObject)
        {
            try
            {
                #region Initialization
                base.Initialize(configuration, true, loggerObject);

                // Setting other fields.
                Address = sbConfiguration.Address;

                // Creating queue client for acknowledgment.
                if (sbConfiguration.Acknowledgment)
                {
                    acknowledgmentQueueClient = queueClient.MessagingFactory.CreateQueueClient(sbConfiguration.QueueName);
                }
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.ServiceBusName,
                          queueName: sbConfiguration.QueueName,
                          address: sbConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Common initialization code.
        /// </summary>
        protected virtual void Initialize(Dictionary <string, string> configuration, ZeroMqSocketType socketType, bool isInbound, IQueueLogger loggerObject = null)
        {
            try
            {
                #region Logger Initialization
                logger = loggerObject;
                #endregion

                #region Parameters Collection
                zmqConfiguration = CommonItems.CollectZmqConfiguration(ref configuration, isInbound, ref logger);
                #endregion

                #region Creating Socket
                InitializeZeroMqSocket(socketType, isInbound);
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.ZeroMqName,
                          address: zmqConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 20
0
        public void StartReceivingMessage()
        {
            try
            {
                lock (queueClient)
                {
                    if (!isReceivingMessages)
                    {
                        // Creating message receiver.
                        messageReceiver = queueClient.MessagingFactory.CreateMessageReceiver(sbConfiguration.QueueName, (sbConfiguration.Acknowledgment ? ReceiveMode.PeekLock : ReceiveMode.ReceiveAndDelete));

                        // Registering event.
                        messageReceiver.OnMessageAsync(ReceiveReadyAsync, new OnMessageOptions {
                            AutoComplete = false, MaxConcurrentCalls = sbConfiguration.MaxConcurrentReceiveCallback
                        });

                        // Updating flag.
                        isReceivingMessages = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToStartReceivingMessage,
                          message: ErrorMessages.FailedToStartReceivingMessage,
                          innerException: ex,
                          queueContext: CommonItems.ServiceBusName,
                          queueName: sbConfiguration.QueueName,
                          address: sbConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 21
0
        public void StopReceivingMessage()
        {
            try
            {
                lock (queueClient)
                {
                    if (isReceivingMessages)
                    {
                        messageReceiver.Close();

                        // Updating flag.
                        isReceivingMessages = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToStopReceivingMessage,
                    message: ErrorMessages.FailedToStopReceivingMessage,
                    innerException: ex,
                    queueContext: CommonItems.ServiceBusName,
                    queueName: sbConfiguration.QueueName,
                    address: sbConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 22
0
        public void SendRequest(TRequest message)
        {
            #region Sending Message
            try
            {
                // Preparing message.
                var correlationId     = Guid.NewGuid().ToString("N");
                var messageProperties = model.CreateBasicProperties();
                messageProperties.ReplyTo       = replyQueueName;
                messageProperties.CorrelationId = correlationId;

                // Storing correlation Id.
                lock (correlationIds)
                {
                    correlationIds.Add(correlationId);
                }

                // Sending message.
                lock (lockForQueueOperation)
                {
                    model.BasicPublish(exchangeName, routingKey, messageProperties, MessageQueueCommonItems.SerializeToJsonBytes(message));
                }
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion

                throw;
            }
            catch (Exception ex)
            {
                #region Adding Context Data
                var context = new Dictionary <string, string>();

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.ExchangeName))
                {
                    context.Add(CommonContextKeys.ExchangeName, rabbitMqConfiguration.ExchangeName);
                }

                if (!string.IsNullOrEmpty(routingKey))
                {
                    context.Add(CommonContextKeys.RoutingKey, routingKey);
                }
                #endregion

                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToSendMessage,
                          message: ErrorMessages.FailedToSendMessage,
                          innerException: ex,
                          queueContext: CommonItems.RabbitMqName,
                          queueName: rabbitMqConfiguration.QueueName,
                          address: rabbitMqConfiguration.Address,
                          context: context,
                          logger: logger);
            }
            #endregion
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private void ResponseReady(object sender, BasicDeliverEventArgs e)
        {
            try
            {
                // Check if correlation Id is valid.
                if (correlationIds.Contains(e.BasicProperties.CorrelationId))
                {
                    lock (correlationIds)
                    {
                        correlationIds.Remove(e.BasicProperties.CorrelationId);
                    }

                    // Converting from Json bytes.
                    var convertedMessage = MessageQueueCommonItems.DeserializeFromJsonBytes <TResponse>(e.Body);

                    // Calling handler.
                    OnResponseReady?.Invoke(convertedMessage);
                }
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                #region Adding Context Data
                var context = new Dictionary <string, string>();

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.ExchangeName))
                {
                    context.Add(CommonContextKeys.ExchangeName, rabbitMqConfiguration.ExchangeName);
                }

                if (!string.IsNullOrEmpty(routingKey))
                {
                    context.Add(CommonContextKeys.RoutingKey, routingKey);
                }

                if (!string.IsNullOrEmpty(replyQueueName))
                {
                    context.Add(CommonContextKeys.ReplyQueueName, replyQueueName);
                }
                #endregion

                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveResponseMessage,
                    message: ErrorMessages.FailedToReceiveResponseMessage,
                    innerException: ex,
                    queueContext: CommonItems.RabbitMqName,
                    queueName: rabbitMqConfiguration.QueueName,
                    address: rabbitMqConfiguration.Address,
                    context: context,
                    logger: logger);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private void ReceiveReady(object sender, BasicDeliverEventArgs request)
        {
            try
            {
                // Converting from Json bytes.
                var convertedMessage = MessageQueueCommonItems.DeserializeFromJsonBytes <TRequest>(request.Body);

                // Getting other required fields for response.
                var replyProperties = model.CreateBasicProperties();
                replyProperties.CorrelationId = request.BasicProperties.CorrelationId;

                // Calling handler.
                OnRequestReady?.Invoke(new RmqRequestMessage <TRequest, TResponse>(
                                           model,
                                           replyProperties,
                                           rabbitMqConfiguration.ExchangeName ?? string.Empty,
                                           request.BasicProperties.ReplyTo,
                                           rabbitMqConfiguration.Acknowledgment,
                                           request.DeliveryTag,
                                           convertedMessage,
                                           ref logger));
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                #region Adding Context Data
                var context = new Dictionary <string, string>();

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.ExchangeName))
                {
                    context.Add(CommonContextKeys.ExchangeName, rabbitMqConfiguration.ExchangeName);
                }

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.RoutingKey))
                {
                    context.Add(CommonContextKeys.RoutingKey, rabbitMqConfiguration.RoutingKey);
                }
                #endregion

                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveRequestMessage,
                    message: ErrorMessages.FailedToReceiveRequestMessage,
                    innerException: ex,
                    queueContext: CommonItems.RabbitMqName,
                    queueName: rabbitMqConfiguration.QueueName,
                    address: rabbitMqConfiguration.Address,
                    context: context,
                    logger: logger);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Common initialization code.
        /// </summary>
        protected virtual void Initialize(Dictionary <string, string> configuration, bool isInbound, IQueueLogger loggerObject = null)
        {
            try
            {
                #region Logger Initialization
                logger = loggerObject;
                #endregion

                #region Parameters Collection
                sbConfiguration = CommonItems.CollectSbConfiguration(ref configuration, isInbound, ref logger);
                #endregion

                #region Initializing Queue
                queueClient = QueueClient.CreateFromConnectionString(sbConfiguration.Address);

                if (!string.IsNullOrWhiteSpace(sbConfiguration.NamespaceAddress))
                {
                    namespaceManager = NamespaceManager.CreateFromConnectionString(sbConfiguration.NamespaceAddress);
                }

                // Updating address field to remove confidential data.
                sbConfiguration.Address          = sbConfiguration.Address?.Split(';')?.FirstOrDefault(x => x.StartsWith(CommonItems.SbConnectionStringAddressPartName, StringComparison.InvariantCultureIgnoreCase));
                sbConfiguration.NamespaceAddress = sbConfiguration.NamespaceAddress?.Split(';')?.FirstOrDefault(x => x.StartsWith(CommonItems.SbConnectionStringAddressPartName, StringComparison.InvariantCultureIgnoreCase));

                if (!IsQueueExistsHelper())
                {
                    throw MessageQueueCommonItems.PrepareAndLogQueueException(
                              errorCode: QueueErrorCode.QueueDoesNotExist,
                              message: ErrorMessages.QueueDoesNotExist,
                              innerException: null,
                              queueContext: CommonItems.ServiceBusName,
                              queueName: sbConfiguration.QueueName,
                              address: sbConfiguration.Address,
                              logger: logger);
                }

                // Updating flag.
                isInitialized = true;
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.ServiceBusName,
                          queueName: sbConfiguration.QueueName,
                          address: sbConfiguration.Address,
                          logger: logger);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private async void ReceiveReady(object sender, BasicDeliverEventArgs e)
        {
            try
            {
                // Converting from Json bytes.
                var convertedMessage      = MessageQueueCommonItems.DeserializeFromJsonBytes <TMessage>(e.Body);
                var messageReceiveOptions = new RmqMessageReceiveOptions(model, e.DeliveryTag, rabbitMqConfiguration.QueueName, rabbitMqConfiguration.Acknowledgment, ref logger);

                // Calling handler (async is preferred over sync).
                if (OnMessageReadyAsync != null)
                {
                    await OnMessageReadyAsync.Invoke(convertedMessage, messageReceiveOptions);
                }
                else
                {
                    OnMessageReady?.Invoke(convertedMessage, messageReceiveOptions);
                }
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                #region Adding Context Data
                var context = new Dictionary <string, string>();

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.ExchangeName))
                {
                    context.Add(CommonContextKeys.ExchangeName, rabbitMqConfiguration.ExchangeName);
                }

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.RoutingKey))
                {
                    context.Add(CommonContextKeys.RoutingKey, rabbitMqConfiguration.RoutingKey);
                }
                #endregion

                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveMessage,
                    message: ErrorMessages.FailedToReceiveMessage,
                    innerException: ex,
                    queueContext: CommonItems.RabbitMqName,
                    queueName: rabbitMqConfiguration.QueueName,
                    address: rabbitMqConfiguration.Address,
                    context: context,
                    logger: logger);
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Helper method to check if queue has been initialized.
 /// </summary>
 private void CheckIfQueueHasInitialized()
 {
     if (!isInitialized)
     {
         throw MessageQueueCommonItems.PrepareAndLogQueueException(
                   errorCode: QueueErrorCode.MessageQueueIsNotInitialized,
                   message: ErrorMessages.MessageQueueIsNotInitialized,
                   innerException: null,
                   queueContext: CommonItems.ServiceBusName,
                   queueName: sbConfiguration?.QueueName,
                   address: sbConfiguration?.Address,
                   logger: logger);
     }
 }
Ejemplo n.º 28
0
        public RmqOutboundRaR(Dictionary <string, string> configuration, IQueueLogger loggerObject)
        {
            try
            {
                #region Initialization
                base.Initialize(configuration, AmqpExchangeType.Direct, false, loggerObject);

                // Setting other fields.
                Address        = rabbitMqConfiguration.Address;
                exchangeName   = rabbitMqConfiguration.ExchangeName ?? string.Empty;
                routingKey     = rabbitMqConfiguration.RoutingKey ?? rabbitMqConfiguration.QueueName;
                replyQueueName = model.QueueDeclare().QueueName;
                correlationIds = new List <string>();

                // Registering event.
                var consumer = new EventingBasicConsumer(model);
                consumer.Received += ResponseReady;

                // Binding with queue.
                model.BasicConsume(replyQueueName, true, consumer);
                #endregion
            }
            catch (Exception ex) when(!(ex is QueueException))
            {
                #region Adding Context Data
                var context = new Dictionary <string, string>();

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.ExchangeName))
                {
                    context.Add(CommonContextKeys.ExchangeName, rabbitMqConfiguration.ExchangeName);
                }

                if (!string.IsNullOrEmpty(rabbitMqConfiguration.RoutingKey))
                {
                    context.Add(CommonContextKeys.RoutingKey, rabbitMqConfiguration.RoutingKey);
                }
                #endregion

                throw MessageQueueCommonItems.PrepareAndLogQueueException(
                          errorCode: QueueErrorCode.FailedToInitializeMessageQueue,
                          message: ErrorMessages.FailedToInitializeMessageQueue,
                          innerException: ex,
                          queueContext: CommonItems.RabbitMqName,
                          queueName: rabbitMqConfiguration.QueueName,
                          address: rabbitMqConfiguration.Address,
                          context: context,
                          logger: logger);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Helper event handler.
        /// </summary>
        private async Task ReceiveReadyAsync(BrokeredMessage brokeredMessage)
        {
            try
            {
                if (brokeredMessage != null)
                {
                    // Converting from Json.
                    var convertedMessage = MessageQueueCommonItems.DeserializeFromJson <TMessage>(new StreamReader(brokeredMessage.GetBody <Stream>()).ReadToEnd());
                    var lockToken        = Guid.Empty;

                    // Getting lock token if acknowledgment is configured.
                    if (sbConfiguration.Acknowledgment)
                    {
                        lockToken = brokeredMessage.LockToken;
                    }

                    var messageReceiveOptions = new SbMessageReceiveOptions(lockToken, sbConfiguration.QueueName, sbConfiguration.Acknowledgment, ref acknowledgmentQueueClient, ref logger);

                    // Calling handler (async is preferred over sync).
                    if (OnMessageReadyAsync != null)
                    {
                        await OnMessageReadyAsync.Invoke(convertedMessage, messageReceiveOptions);
                    }
                    else
                    {
                        OnMessageReady?.Invoke(convertedMessage, messageReceiveOptions);
                    }
                }
            }
            catch (QueueException queueException)
            {
                #region Logging - Error
                logger.Fatal(queueException, queueException.Message);
                #endregion
            }
            catch (Exception ex)
            {
                MessageQueueCommonItems.PrepareAndLogQueueException(
                    errorCode: QueueErrorCode.FailedToReceiveMessage,
                    message: ErrorMessages.FailedToReceiveMessage,
                    innerException: ex,
                    queueContext: CommonItems.ServiceBusName,
                    queueName: sbConfiguration.QueueName,
                    address: sbConfiguration.Address,
                    logger: logger);
            }
        }
Ejemplo n.º 30
0
 public bool HasMessage()
 {
     try
     {
         return(socket.HasIn);
     }
     catch (Exception ex)
     {
         throw MessageQueueCommonItems.PrepareAndLogQueueException(
                   errorCode: QueueErrorCode.FailedToCheckQueueHasMessage,
                   message: ErrorMessages.FailedToCheckQueueHasMessage,
                   innerException: ex,
                   queueContext: CommonItems.ZeroMqName,
                   address: zmqConfiguration.Address,
                   logger: logger);
     }
 }