Chat Application With ASP.NET MVC Using RabbitMQ

Spread the love

Chat Application With ASP.NET MVC Using RabbitMQ

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using RabbitMQ.Client;  
  6. using RabbitMQ.Util;  
  7. using System.Web.Mvc;  
  8. using ChatApplication.Models.HelperBll;  
  9. using System.Web.UI.WebControls;  
  10.   
  11. namespace ChatApplication.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         DataLayer dl = new DataLayer();  
  16.         // GET: Home  
  17.         public ActionResult Index()  
  18.         {  
  19.             if (Session[“userid”]==null)  
  20.             {  
  21.                 return RedirectToAction(“login”);  
  22.             }  
  23.             else  
  24.             {  
  25.                 return View();  
  26.             }  
  27.         }  
  28.         [HttpPost]  
  29.         public JsonResult sendmsg(string message,string friend)  
  30.         {  
  31.             RabbitMQBll obj = new RabbitMQBll();  
  32.             IConnection con = obj.GetConnection();  
  33.             bool flag = obj.send(con, message,friend);  
  34.             return Json(null);  
  35.         }  
  36.         [HttpPost]  
  37.         public JsonResult receive()  
  38.         {  
  39.             try  
  40.             {  
  41.                 RabbitMQBll obj = new RabbitMQBll();  
  42.                 IConnection con = obj.GetConnection();  
  43.                 string userqueue = Session[“username”].ToString();  
  44.                 string message = obj.receive(con, userqueue);  
  45.                 return Json(message);  
  46.             }  
  47.             catch (Exception)  
  48.             {  
  49.   
  50.                 return null;  
  51.             }  
  52.   
  53.              
  54.         }  
  55.         public ActionResult login()  
  56.         {  
  57.   
  58.             return View();  
  59.         }  
  60.         [HttpPost]  
  61.         public ActionResult login(FormCollection fc)  
  62.         {  
  63.             string email = fc[“txtemail”].ToString();  
  64.             string password = fc[“txtpassword”].ToString();  
  65.             UserModel user = dl.login(email, password);  
  66.             if (user.userid > 0)  
  67.             {  
  68.                 ViewData[“status”] = 1;  
  69.                 ViewData[“msg”] = “login Successful…”;  
  70.                 Session[“username”] = user.email;  
  71.                 Session[“userid”] = user.userid.ToString();  
  72.                 return RedirectToAction(“Index”);  
  73.             }  
  74.             else  
  75.             {  
  76.   
  77.                 ViewData[“status”] = 2;  
  78.                 ViewData[“msg”] = “invalid Email or Password…”;  
  79.                 return View();  
  80.             }  
  81.   
  82.         }  
  83.   
  84.         [HttpPost]  
  85.         public JsonResult friendlist()  
  86.         {  
  87.             int id = Convert.ToInt32(Session[“userid”].ToString());  
  88.             List<UserModel> users = dl.getusers(id);  
  89.             List<ListItem> userlist = new List<ListItem>();  
  90.             foreach (var item in users)  
  91.             {  
  92.                 userlist.Add(new ListItem  
  93.                 {  
  94.                     Value = item.email.ToString(),  
  95.                     Text = item.email.ToString()  
  96.   
  97.                 });  
  98.             }  
  99.             return Json(userlist);  
  100.         }  
  101.     }  
  102. }   

Create a table in the database (PostgreSQL).

Below is the query to create a table.

  1. CREATE TABLE public.tbluser(userid integer NOT NULL DEFAULT nextval(‘tbluser_userid_seq’::regclass), email text COLLATE pg_catalog.  
  2.     “default”  
  3.     NOT NULL, mobile text COLLATE pg_catalog.  
  4.     “default”  
  5.     NOT NULL, password text COLLATE pg_catalog.  
  6.     “default”  
  7.     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.

  1. public class UserModel  
  2.     {  
  3.         public int userid { getset; }  
  4.         [Required(ErrorMessage =”Email id Is required”)]  
  5.         public string email { getset; }  
  6.         [Required(ErrorMessage = “Mobile Number Is required”)]  
  7.         public string mobile { getset; }  
  8.         [Required(ErrorMessage = “Password Is required”)]  
  9.         public string password { getset; }  
  10.         [Required(ErrorMessage = “Confirm Password Is required”)]  
  11.         [Compare(“password”, ErrorMessage = “Password and Confirmation Password must match.”)]  
  12.         public string confirmpassword { getset; }  
  13.         [Required(ErrorMessage = “Date Of Birth Is required”)]  
  14.         public string dob { getset; }  
  15.     }  

Create a class Datalayer.cs and paste it.

Right-click on Models folder ->click Add-> select Class.

Paste the below code in DataLayer.cs.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using RabbitMQ.Client;  
  6. using RabbitMQ.Util;  
  7. using System.Web.Mvc;  
  8. using ChatApplication.Models.HelperBll;  
  9. using System.Web.UI.WebControls;  
  10.   
  11. namespace ChatApplication.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         DataLayer dl = new DataLayer();  
  16.         // GET: Home  
  17.         public ActionResult Index()  
  18.         {  
  19.             if (Session[“userid”]==null)  
  20.             {  
  21.                 return RedirectToAction(“login”);  
  22.             }  
  23.             else  
  24.             {  
  25.                 return View();  
  26.             }  
  27.         }  
  28.         [HttpPost]  
  29.         public JsonResult sendmsg(string message,string friend)  
  30.         {  
  31.             RabbitMQBll obj = new RabbitMQBll();  
  32.             IConnection con = obj.GetConnection();  
  33.             bool flag = obj.send(con, message,friend);  
  34.             return Json(null);  
  35.         }  
  36.         [HttpPost]  
  37.         public JsonResult receive()  
  38.         {  
  39.             try  
  40.             {  
  41.                 RabbitMQBll obj = new RabbitMQBll();  
  42.                 IConnection con = obj.GetConnection();  
  43.                 string userqueue = Session[“username”].ToString();  
  44.                 string message = obj.receive(con, userqueue);  
  45.                 return Json(message);  
  46.             }  
  47.             catch (Exception)  
  48.             {  
  49.   
  50.                 return null;  
  51.             }  
  52.   
  53.              
  54.         }  
  55.         public ActionResult login()  
  56.         {  
  57.   
  58.             return View();  
  59.         }  
  60.         [HttpPost]  
  61.         public ActionResult login(FormCollection fc)  
  62.         {  
  63.             string email = fc[“txtemail”].ToString();  
  64.             string password = fc[“txtpassword”].ToString();  
  65.             UserModel user = dl.login(email, password);  
  66.             if (user.userid > 0)  
  67.             {  
  68.                 ViewData[“status”] = 1;  
  69.                 ViewData[“msg”] = “login Successful…”;  
  70.                 Session[“username”] = user.email;  
  71.                 Session[“userid”] = user.userid.ToString();  
  72.                 return RedirectToAction(“Index”);  
  73.             }  
  74.             else  
  75.             {  
  76.   
  77.                 ViewData[“status”] = 2;  
  78.                 ViewData[“msg”] = “invalid Email or Password…”;  
  79.                 return View();  
  80.             }  
  81.   
  82.         }  
  83.   
  84.         [HttpPost]  
  85.         public JsonResult friendlist()  
  86.         {  
  87.             int id = Convert.ToInt32(Session[“userid”].ToString());  
  88.             List<UserModel> users = dl.getusers(id);  
  89.             List<ListItem> userlist = new List<ListItem>();  
  90.             foreach (var item in users)  
  91.             {  
  92.                 userlist.Add(new ListItem  
  93.                 {  
  94.                     Value = item.email.ToString(),  
  95.                     Text = item.email.ToString()  
  96.   
  97.                 });  
  98.             }  
  99.             return Json(userlist);  
  100.         }  
  101.     }  
  102. }   

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using RabbitMQ.Client;  
  6. using RabbitMQ.Util;  
  7. using RabbitMQ.Client.Events;  
  8. using System.Text;  
  9.   
  10. namespace ChatApplication.Models.HelperBll  
  11. {  
  12.     public class RabbitMQBll  
  13.     {  
  14.         public IConnection GetConnection()  
  15.         {  
  16.             ConnectionFactory factory = new ConnectionFactory();  
  17.             factory.UserName = “”;  
  18.             factory.Password = “”;  
  19.             factory.Port = 5672;  
  20.             factory.HostName = “localhost”;  
  21.             factory.VirtualHost = “/”;  
  22.              
  23.             return factory.CreateConnection();  
  24.         }  
  25.         public bool send(IConnection con,string message,string friendqueue)  
  26.         {  
  27.             try  
  28.             {  
  29.                 IModel channel = con.CreateModel();  
  30.                 channel.ExchangeDeclare(“messageexchange”, ExchangeType.Direct);  
  31.                 channel.QueueDeclare(friendqueue, truefalsefalsenull);  
  32.                 channel.QueueBind(friendqueue, “messageexchange”, friendqueue, null);  
  33.                 var msg = Encoding.UTF8.GetBytes(message);  
  34.                 channel.BasicPublish(“messageexchange”, friendqueue, null, msg);  
  35.                   
  36.             }  
  37.             catch (Exception)  
  38.             {  
  39.   
  40.                   
  41.             }  
  42.             return true;  
  43.   
  44.         }  
  45.         public string receive(IConnection con,string myqueue)  
  46.         {  
  47.             try  
  48.             {  
  49.                 string queue = myqueue;  
  50.                 IModel channel = con.CreateModel();  
  51.                 channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);  
  52.                 var consumer = new EventingBasicConsumer(channel);  
  53.                 BasicGetResult result = channel.BasicGet(queue: queue, autoAck: true);  
  54.                 if (result != null)  
  55.                     return Encoding.UTF8.GetString(result.Body);  
  56.                 else  
  57.                     return null;  
  58.             }  
  59.             catch (Exception)  
  60.             {  
  61.                 return null;  
  62.                   
  63.             }  
  64.              
  65.         }  
  66.     }  
  67. }  

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.

  1. @using System.Web.Optimization  
  2. @{  
  3.     Layout = null;  
  4. }  
  5.   
  6. <!DOCTYPE html>  
  7.   
  8. <html>  
  9. <head>  
  10.     <meta name=”viewport” content=”width=device-width” />  
  11.     <title>Index</title>  
  12.     @Styles.Render(“~/Content/css”)  
  13.     @Scripts.Render(“~/bundles/jquery”)  
  14.     @Scripts.Render(“~/bundles/bootstrap”)  
  15.     <script type=”text/javascript”>  
  16.         $(document).ready(function () {  
  17.             $(“#btnsend”).click(function () {  
  18.                 send();  
  19.             });  
  20.             getmyfriends();  
  21.             function getmyfriends()  
  22.             {  
  23.                 $.ajax({  
  24.                     type: “POST”,  
  25.                     url: “@Url.Action(“friendlist”)”,  
  26.                     contentType: “application/json; charset=utf-8”,  
  27.                     data: ‘{}’,  
  28.                     dataType: “json”,  
  29.                     success: function (r) {  
  30.                         var ddlfrined = $(“[id*=ddlfriend]”);  
  31.                         // ddlfrined.empty().append(‘<option selected=”selected” value=”0″>select</option>’);  
  32.                         for (var i = 0; i <r.length; i++) {  
  33.                             ddlfrined.append($(“<option></option>”).val(r[i].Value).html(r[i].Text));  
  34.                         }   
  35.                     },  
  36.                     error: function (r) {  
  37.                         alert(“error”);  
  38.                     }  
  39.                 });  
  40.             }  
  41.             setInterval(function () {  
  42.                 $.ajax({  
  43.                     type: “POST”,  
  44.                     contentType: “application/json; charset=utf-8”,  
  45.                     data: ‘{}’,  
  46.                     url: “@Url.Action(“receive”)”,  
  47.                     dataType: “json”,  
  48.                     success: function (response) {  
  49.                         var data = $(“#divmsg”).html();  
  50.                         $(“#divmsg”).html(data + “<br>Friend:” + response);  
  51.                           
  52.                     },  
  53.                     error: function (response) {  
  54.                          
  55.                     }  
  56.                 });  
  57.             }, 5000);  
  58.             function send() {  
  59.                 var message = $(“#txtmsg”).val();  
  60.                 var friend = $(“#ddlfriend”).val();  
  61.                 var data = $(“#divmsg”).html();  
  62.                 $(“#divmsg”).html(data + “<br>Me:” + message);  
  63.                 $(“#txtmsg”).val(“”);  
  64.                 debugger;  
  65.                 $.ajax({  
  66.                     type: “POST”,  
  67.                     contentType: “application/json; charset=utf-8”,  
  68.                     data: ‘{“message”:”‘ + message + ‘”,”friend”:”‘+friend+'”}’,  
  69.                     url: “@Url.Action(“sendmsg”)”,  
  70.                     dataType: “json”,  
  71.                     success: function (response) {  
  72.                         var data = $(“#divmsg”).html();  
  73.                         $(“#divmsg”).html(data + “<br>Me :” + message);  
  74.                     },  
  75.                     error: function (response) {  
  76.   
  77.                     }  
  78.                 });  
  79.             }  
  80.         });  
  81.     </script>  
  82. </head>  
  83. <body>  
  84.     <nav class=”nav navbar-default”>  
  85.         <div class=”navbar-brand”>  
  86.            <span style=”float:right;”>@Session[“username”].ToString()</span>  
  87.         </div>  
  88.     </nav>  
  89.     <br />  
  90.     <div class=”clearfix”></div>  
  91.     @using (Html.BeginForm())  
  92.     {  
  93.         <div class=”container”>  
  94.             <div class=”row”>  
  95.                  
  96.             </div>  
  97.             <div class=”row”>  
  98.                 <div class=”col-md-4″>  
  99.                     <div class=”form-group”>  
  100.                         <select id=”ddlfriend” name=”ddlfriend” class=”form-control”>  
  101.   
  102.                         </select>  
  103.                     </div>  
  104.                     <div class=”form-group”>  
  105.                         <input type=”text” name=”txtmsg” id=”txtmsg” class=”form-control” />  
  106.                     </div>  
  107.                     <div class=”form-group”>  
  108.                         <input type=”button” value=”send” class=”btn btn-success” name=”btnsend” id=”btnsend” />  
  109.                     </div>  
  110.                 </div>  
  111.                 <div class=”col-md-6″>  
  112.                     <div class=”panel panel-success”>  
  113.                         <div class=”panel-heading”>  
  114.                             <div class=”panel-title”>  
  115.                                 Messages  
  116.                             </div>  
  117.                             <div class=”panel-footer” style=”min-height:400px;”>  
  118.                                 <div id=”divmsg”>  
  119.                                 </div>  
  120.                             </div>  
  121.                         </div>  
  122.                     </div>  
  123.                 </div>  
  124.             </div>  
  125.         </div>  
  126.     }  
  127.     <div>  
  128.    </div>  
  129. </body>  
  130. </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.

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com