In this article, you will learn how to develop a chat application in ASP.NET MVC using RabbitMQ. First, you need to download RabbitMQ and OTP.
Step 1: RabbitMQ
https://www.rabbitmq.com/download.html
Step 2: OTP
http://www.erlang.org/downloads
Create a new MVC project.
Step 3: Open Visual Studio
Go to File menu and select New Project->Web application->MVC.
From New Project, select ASP.NET Web Application and click OK.
Select MVC and click OK.
In Visual Studio, the folder structure is shown as below in the Solution Explorer for the chat application.
Right-click on Project and select "Manage NuGet Packages..".
Search Rabbitmq and install the rabbitmq.client package.
Adding new HomeController
Right-click on Controllers folder, click Add >> Controller.
Once the user selects the controller, the "Add Scaffold" dialog gets opened. Select MVC 5 Controller – Empty and click "Add" button.
Give Controller a name (HomeController) and click "Add".
Once the user clicks on Add button, the Workspace will be opened to write the code.
Paste the below code in HomeController.
Create a table in the database (PostgreSQL).
Below is the query to create a table.
- CREATE TABLE public.tbluser(userid integer NOT NULL DEFAULT nextval('tbluser_userid_seq'::regclass), email text COLLATE pg_catalog.
- "default"
- NOT NULL, mobile text COLLATE pg_catalog.
- "default"
- NOT NULL, password text COLLATE pg_catalog.
- "default"
- NOT NULL, dob date NOT NULL, CONSTRAINT tbluser_pkey PRIMARY KEY(userid))
Insert the connection string in web.config file in ASP.NET.
Create a User Model in the Models folder. Right-click on Models folder -> click Add -> select Class.
Paste the below code in UserModel.
- public class UserModel
- {
- public int userid { get; set; }
- [Required(ErrorMessage ="Email id Is required")]
- public string email { get; set; }
- [Required(ErrorMessage = "Mobile Number Is required")]
- public string mobile { get; set; }
- [Required(ErrorMessage = "Password Is required")]
- public string password { get; set; }
- [Required(ErrorMessage = "Confirm Password Is required")]
- [Compare("password", ErrorMessage = "Password and Confirmation Password must match.")]
- public string confirmpassword { get; set; }
- [Required(ErrorMessage = "Date Of Birth Is required")]
- public string dob { get; set; }
- }
Create a class Datalayer.cs and paste it.
Right-click on Models folder ->click Add-> select Class.
Paste the below code in DataLayer.cs.
Create a class RabbitMQBll.cs to handle the Rabbitmq operations (connection, send and receive). Right-click on Models folder -> click Add -> select Class.
Paste the below code in RabbitMQBll.cs.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using RabbitMQ.Client;
- using RabbitMQ.Util;
- using RabbitMQ.Client.Events;
- using System.Text;
-
- namespace ChatApplication.Models.HelperBll
- {
- public class RabbitMQBll
- {
- public IConnection GetConnection()
- {
- ConnectionFactory factory = new ConnectionFactory();
- factory.UserName = "";
- factory.Password = "";
- factory.Port = 5672;
- factory.HostName = "localhost";
- factory.VirtualHost = "/";
-
- return factory.CreateConnection();
- }
- public bool send(IConnection con,string message,string friendqueue)
- {
- try
- {
- IModel channel = con.CreateModel();
- channel.ExchangeDeclare("messageexchange", ExchangeType.Direct);
- channel.QueueDeclare(friendqueue, true, false, false, null);
- channel.QueueBind(friendqueue, "messageexchange", friendqueue, null);
- var msg = Encoding.UTF8.GetBytes(message);
- channel.BasicPublish("messageexchange", friendqueue, null, msg);
-
- }
- catch (Exception)
- {
-
-
- }
- return true;
-
- }
- public string receive(IConnection con,string myqueue)
- {
- try
- {
- string queue = myqueue;
- IModel channel = con.CreateModel();
- channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
- var consumer = new EventingBasicConsumer(channel);
- BasicGetResult result = channel.BasicGet(queue: queue, autoAck: true);
- if (result != null)
- return Encoding.UTF8.GetString(result.Body);
- else
- return null;
- }
- catch (Exception)
- {
- return null;
-
- }
-
- }
- }
- }
Add the below code in Views -> Index.cshtml.
Right-click on Index method in HomeController ->Add View.
Give the Index name.
Paste the below code in View.
- @using System.Web.Optimization
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- <script type="text/javascript">
- $(document).ready(function () {
- $("#btnsend").click(function () {
- send();
- });
- getmyfriends();
- function getmyfriends()
- {
- $.ajax({
- type: "POST",
- url: "@Url.Action("friendlist")",
- contentType: "application/json; charset=utf-8",
- data: '{}',
- dataType: "json",
- success: function (r) {
- var ddlfrined = $("[id*=ddlfriend]");
-
- for (var i = 0; i <r.length; i++) {
- ddlfrined.append($("<option></option>").val(r[i].Value).html(r[i].Text));
- }
- },
- error: function (r) {
- alert("error");
- }
- });
- }
- setInterval(function () {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- data: '{}',
- url: "@Url.Action("receive")",
- dataType: "json",
- success: function (response) {
- var data = $("#divmsg").html();
- $("#divmsg").html(data + "<br>Friend:" + response);
-
- },
- error: function (response) {
-
- }
- });
- }, 5000);
- function send() {
- var message = $("#txtmsg").val();
- var friend = $("#ddlfriend").val();
- var data = $("#divmsg").html();
- $("#divmsg").html(data + "<br>Me:" + message);
- $("#txtmsg").val("");
- debugger;
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- data: '{"message":"' + message + '","friend":"'+friend+'"}',
- url: "@Url.Action("sendmsg")",
- dataType: "json",
- success: function (response) {
- var data = $("#divmsg").html();
- $("#divmsg").html(data + "<br>Me :" + message);
- },
- error: function (response) {
-
- }
- });
- }
- });
- </script>
- </head>
- <body>
- <nav class="nav navbar-default">
- <div class="navbar-brand">
- <span style="float:right;">@Session["username"].ToString()</span>
- </div>
- </nav>
- <br />
- <div class="clearfix"></div>
- @using (Html.BeginForm())
- {
- <div class="container">
- <div class="row">
-
- </div>
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <select id="ddlfriend" name="ddlfriend" class="form-control">
-
- </select>
- </div>
- <div class="form-group">
- <input type="text" name="txtmsg" id="txtmsg" class="form-control" />
- </div>
- <div class="form-group">
- <input type="button" value="send" class="btn btn-success" name="btnsend" id="btnsend" />
- </div>
- </div>
- <div class="col-md-6">
- <div class="panel panel-success">
- <div class="panel-heading">
- <div class="panel-title">
- Messages
- </div>
- <div class="panel-footer" style="min-height:400px;">
- <div id="divmsg">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- }
- <div>
- </div>
- </body>
- </html>
Press F5 to Build and Run the project.
I hope you liked the article. If you have any query, please feel free to post in the comments section.