Building a Group chat app with .NET and pusher

Published Dec 11, 2017

Our human need for real-time communication is always evolving. That’s why we’re seeing a rise of chat features in more than just chat-based apps.

In this article, we’ll build a group chat application in ASP.NET MVC.

Pusher sits as a real-time layer between our servers and clients. We’ll utilize pusher’s technology to add real-time functionality to our app.

Prerequisite

To follow along you should know the basics of:

  • ASP .NET MVC
  • JavaScript (jQuery)

Setting Up Pusher App

  • Sign up or login to your Pusher account.
  • Create a new pusher app.

Creating a Pusher app

Note down your Pusher app details you just created.

app_id  = "*********"
key     = "***********************"
secret  =  "*********************"
cluster = "**"

Setting up ASP.NET MVC Project

Create a new ASP.NET MVC application using your favorite IDE or editor. In this tutorial, I’ll be using Visual Studio.

Creating an ASP.NET MVC project

Now install Pusher’s .NET library through the package manager console.

PM> Install-Package PusherServer

If everything goes fine at this point, we are ready to start building our group chat app. You should have noticed that our application has authentication (Identity) available for us, so we don’t need to implement it again.

Designing the view

Let’s quickly craft an interface for our chat application using HTML. Replace the content in Views/Home/Index.cshtml with the below:

    <!-- Views/Home/Index.cshtml -->
    @{
        ViewBag.Title = "Home Page";
    }
     
    <h1> .NET Group </h1>
     
    <div class="container">
        <div class="row">
            <div class="col-md-4"> </div>
                <div class="col-md-4">
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            <span class="glyphicon glyphicon-comment"></span> ASP
                            <div class="btn-group pull-right">
                                <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                    <span class="glyphicon glyphicon-chevron-down"></span>
                                </button>
                                <ul class="dropdown-menu slidedown">
                                    <li>
                                        <a href="http://www.jquery2dotnet.com">
                                            <span class="glyphicon glyphicon-refresh">
                                            </span>Refresh
                                        </a>
                                    </li>
                                    <li>
                                        <a href="http://www.jquery2dotnet.com">
                                            <span class="glyphicon glyphicon-ok-sign">
                                            </span>Available
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="panel-body">
                            <ul class="chat" id="chat-body"></ul>
                        </div>
                        <div class="panel-footer">
                            <div class="input-group">
                                <input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." />
                                <span class="input-group-btn">
                                    <button class="btn btn-warning btn-sm" id="btn-chat">
                                        Send
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4"> </div>
            </div>
    </div>

Now add the chat application CSS styling to Content/Site.``css:

    .chat
    {
        list-style: none;
        margin: 0;
        padding: 0;
    }
    
    .chat li
    {
        margin-bottom: 10px;
        padding-bottom: 5px;
        border-bottom: 1px dotted #B3A9A9;
    }
    
    .chat li.left .chat-body
    {
        margin-left: 60px;
    }
    
    .chat li.right .chat-body
    {
        margin-right: 60px;
    }
    
    
    .chat li .chat-body p
    {
        margin: 0;
        color: #777777;
    }
    
    .panel .slidedown .glyphicon, .chat .glyphicon
    {
        margin-right: 5px;
    }
    
    .panel-body
    {
        overflow-y: scroll;
        height: 250px;
    }
    
    ::-webkit-scrollbar-track
    {
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
        background-color: #F5F5F5;
    }
    
    ::-webkit-scrollbar
    {
        width: 12px;
        background-color: #F5F5F5;
    }
    
    ::-webkit-scrollbar-thumb
    {
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
        background-color: #555;
    }

Here, we defined the structure of how our app interface will look like. If you have been following closely, below is how your interface should look:

Chat interface

Add JavaScript code for populating chat messages

Next, Create a new file Scripts/custom.js and add the following code to it:

    function append_message(user_name, message) {
     
            return '<li class="right clearfix">' +
                      '<div class="chat-body clearfix">' +
                            '<div class="header">' +
                                '<strong class="pull-left primary-font">' + user_name + '</strong><br>' +
                            '</div>' +
                            '<p>' +
                                message +
                            '</p>' +
                      '</div>' +
                    '</li>';
    }

Here we defined a function that returns an HTML payload that will be used to display chat messages.

Include all necessary JavaScript files

Next, we’ll require Pusher’s JavaScript library file and the Scripts/custom.js JavaScript file we just created in the layout file.

Update Shared/_Layouts.cshtml with the following code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
     
    </head>
    <body>
       ...
        @Scripts.Render("~/bundles/jquery")
        
        <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
        @Scripts.Render("~/Scripts/custom.js")
        
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
      ...
    </body>
    </html>

Now, update the Scripts/custom.js file with the following code:

        var pusher = new Pusher('<INSERT_PUSHER_APP_KEY_HERE>', {
            cluster: '**', //PUSHER APP CLUSTER
            encrypted: true
        });
     
        var channel = pusher.subscribe('dotNetGroupChat');
        channel.bind('asp-event', function (data) {
        
            $("#chat-body").append(append_message(data.userName, data.message));
        });

The above code listens for an incoming message from Pusher and displays them when they are received.

Update the Scripts/custom.js file again with the below code:

        $("#btn-chat").click(function () {
     
            $.post("/Message/Create", { message: $("#btn-input").val() });
            
            $("#btn-input").val('');
     
        })

Here, we are making a POST request with the chat message to our route - /``Message/Create - when the send button is clicked.

If you have followed closely, your custom.js file should look exactly like below:

    var pusher = new Pusher('<INSERT_PUSHER_APP_KEY_HERE>', {
          cluster: 'eu',
          encrypted: true
    });
     
    var channel = pusher.subscribe('dotNetGroupChat');
        channel.bind('asp-event', function (data) {
        
        $("#chat-body").append(append_message(data.userName, data.message));
    });
     
      
    $("#btn-chat").click(function () {
     
        $.post("/Message/Create", { message: $("#btn-input").val() });
            
        $("#btn-input").val('');
     
    })

Creating the Controller for sending of messages to Pusher

Next, Create a new controller called MessageController.cs. We are going to define our messaging logic inside this controller.

Add the below code to MessageController.cs:

    using PusherServer;
    using System.Net;
    using System.Threading.Tasks;
    using System.Web.Mvc;
     
    namespace GroupChat.Controllers
    {
        public class MessageController : Controller
        {
        
            [HttpPost]
            public async Task<ActionResult> Create(string message)
            {
     
                var userName = User.Identity.Name;
     
                var options = new PusherOptions
                {
                    Cluster = "eu", //Repalce with your cluster 
                    Encrypted = true
                };
     
                var pusher = new Pusher(
                  "******", // Replace with your app_id
                  "*****************", //Replace with your key
                  "*****************", //Replace with your secret 
                  options);
     
                var result = await pusher.TriggerAsync(
                  "dotNetGroupChat", //Replace with your chanel name
                  "asp-event",    //Replace with your event name
                  new { message = message, userName = userName });
     
                  return new HttpStatusCodeResult((int)HttpStatusCode.OK);
            }
     
        }
     
    }

Don’t forget to replace those ****``*``** above with your real Pusher app details.

Here, we created a new Controller MessageController which has a method called Create that accepts a post parameter: message. This means we have created a new route - /Message/Create.

We also got the logged in user name using:

var userName = User.Identity.Name;

The method above(Create) accepts a POST request, then sends our data to Pushers Server.

We sent only the chat message and userName to Pusher. Note that you can send any amount of data your app needs here.

{ message = message, userName = userName }

Testing the group chat application

Let’s test what we’ve built. login/register to a user account and start chatting!

Group chat sample

Conclusion

So far, we have seen the basics of how to create a group chat application in ASP.NET MVC leveraging Pusher as a technology for adding real-time functionality. We’ve been able to see how to use Pusher’s technology to add real-time to our chat app. There are lots of creative things you can still add here. We’d be glad to hear what you think in the comments below.

Discover and read more posts from Onwuka Gideon
get started