Using RabbitMQ in C# (II) Sending message to RabbitMQ

13 Aug

Create a Winform application, add below UI to the form:


Add RabbitMQ .net client library in Visual Studio by using Nuget: to install RabbitMQ.Client, run the following command in the Package Manager Console

PM> Install-Package RabbitMQ.Client

Add below code in Form.Load() function

private void Form1_Load(object sender, EventArgs e)
            UserNameTextBox.Text = “guest”;
            PasswordTextBox.Text = “guest”;
            HostTextBox.Text = “localhost”;
            PortTextBox.Text = “5672”;

            //This works
            //factory.UserName = UserNameTextBox.Text;
            //factory.Password = PasswordTextBox.Text;
            //factory.VirtualHost = “/”;
            //factory.HostName = HostTextBox.Text;

            factory.Uri = string.Format(“amqp://{0}:{1}@{2}:{3}{4}”,
                UserNameTextBox.Text, PasswordTextBox.Text,
                HostTextBox.Text, PortTextBox.Text, “/”);

            conn = factory.CreateConnection();
            if (conn == null)
                LogListBox.Items.Add(“Connection Fails”);
                LogListBox.Items.Add(“Connection Success”);

            PubChannel = conn.CreateModel();
            LogListBox.Items.Add(PubChannel == null ? “pub channel creation fails” :
                                                      “pub channel creation success”);

Add event handler for the button “Send”:

var msg = MessageTextBox.Text;
if (string.IsNullOrEmpty(msg))
byte[] messageBodyBytes = Encoding.UTF8.GetBytes(msg);
PubChannel.BasicPublish(exchangeName, routingKey, null, messageBodyBytes);
LogListBox.Items.Add("Sending Message: " + msg);

If you follow the previous post, the variables are set as follows:

string exchangeName = "Demo";
string queueName ="example", routingKey = "example";       

Run the application, and click the Send button, go to web admin page, you will see your messages are sent there!

image image

1 Comment

Posted by on August 13, 2015 in Dotnet/C#, Programming


Tags: , , , , , , , , ,

One response to “Using RabbitMQ in C# (II) Sending message to RabbitMQ

  1. dineshramitc

    August 14, 2015 at 3:52 pm

    Reblogged this on Dinesh Ram Kali..


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: