Receive Message


using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
public partial class Queue
{
    public static string ReceiveMessage(string hostname, int port, string queuename, string username, string password)
    {
        try
        {
            string message = null;

            // RabbitMQ server connection parameters
            ConnectionFactory factory = new ConnectionFactory
            {
                HostName = hostname,
                Port = port,
                UserName = username,
                Password = password,
                VirtualHost = "/",
                ContinuationTimeout = new TimeSpan(1, 0, 0, 0)
            };

            // Create a connection to the RabbitMQ server
            IConnection connection = factory.CreateConnection();

            // Create a channel
            IModel channel = connection.CreateModel();

            // Declare a queue
            channel.QueueDeclare(queuename, true, false, false, null);

            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

            BasicGetResult result = channel.BasicGet(queuename, true);

            if (result != null)
            {
                message = Encoding.UTF8.GetString(result.Body.ToArray());
            }

            return message;
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
    }
}