Building a messenger app using .NET

building-a-messenger-app-using-net-header.png

In this tutorial, we will consider how to build a messenger application using C# .NET.

Introduction

In this tutorial, we will consider how to build a messenger application using C# .NET.

Communication in our current age is largely digital, and the most popular form of digital communication is Instant Messaging. Some applications include some form of chat implementation e.g. Slack or Facebook.

To follow along with this tutorial, you will require:
– Visual Studio, an IDE popularly used for building .NET projects. View installation details here.
– Basic knowledge of C#.
– Basic knowledge of .NET MVC.
– Basic knowledge of JavaScript (jQuery).

Setting up Our Chat Project

Using our Visual Studio IDE, we’ll create our chat project by following the New Project wizard.

We will:
– Set C# as our language to use.
– Select .NET MVC Project as the template.
– Fill in the Project name e.g. HeyChat.
– Fill in the Solution name i.e. application name.

Creating Our Chat App

Defining Pages and Routes

For the purpose of this tutorial, our chat app will consist of 2 pages:
– The front page – where our user signs up.
– The chat view – where our user selects a contact and exchanges messages.

To achieve these views, we will need the following routes:
– The route to render the front page.
– The route to implement login.
– The route to render the chat page.

? These routes only render the views and implement user login. We’ll add more routes as we go along.

Adding these routes to our RouteConfig.cs file we’ll have:

1routes.MapRoute(
2        name: "Home",
3        url: "",
4        defaults: new { controller = "Home", action = "Index" }
5    );
6
7    routes.MapRoute(
8        name: "Login",
9        url: "login",
10        defaults: new { controller = "Auth", action = "Login" }
11    );
12
13    routes.MapRoute(
14        name: "ChatRoom",
15        url: "chat",
16        defaults: new { controller = "Chat", action="Index"}
17    );

These route definitions specify the route pattern and the Controller and Action to handle it.

? Creating our project with Visual Studio automatically creates the HomeContoller.cs file with an Index action. We will use this for our home route.

In our HomeController.cs we’ll render the front page where our users can log in with:

1//HomeController.cs
2
3    // ...
4    Using System.Web.Mvc;
5    // ...
6    public class HomeController : Controller
7    {
8        public ActionResult Index()
9        {
10            if ( Session["user"] != null ) {
11                return Redirect("/chat");
12            }
13
14            return View();
15        }
16    }

? The **View** function creates a view response which we return. When it is invoked, C# looks for the default view of the calling controller class. This default view is the **index.cshtml** file found in the Views directory, in a directory with the same name as the Controller i.e. The default view of the HomeController class will be the **Views/Home/index.cshtml** file.

Setting up Our Database

In order to implement our login feature, we’ll need a database to store users. There are several database drivers to choose from but, in this tutorial, we’ll use the MySQL database driver along with a .NET ORM called Entity Framework.

We will start by installing the MySql.Data.Entities package via NuGet (.NET’s package manager). And then, we’ll install the Entity ******Framework** package also via NuGet, to provide us with our ORM functionality.

? To install packages using NuGet, right-click the Packages folder in our project solution; select the **Add Package** option; and search and select your desired package.

Once our packages have been installed, we will begin setting up our database connection and communication.

First, we will add our database connection credentials to the Web.config file found in our solution folder. In Web.config we will add:

1<connectionStrings>
2        <add name="YourConnectionName" connectionString="Server=localhost;Database=database_name;Uid=root;Pwd=YourPassword;" providerName="MySql.Data.MySqlClient" />
3    </connectionStrings>

⚠️ You will need to replace the placeholder values in the snippet above with actual values database values.

The Web.config file is an XML file and the above connectionStrings element will be added in the body of the configuration element of the file.

Next, we’ll create a Models folder inside our solution folder (on the same folder level as Controllers). In this folder, we will create our model class – this class is a representation of our table. For the login feature we will create the User.cs file. In this class file, we will add the properties of our model:

1// File: User.cs file
2
3    using System;
4    using System.Collections.Generic;
5    namespace HeyChat.Models
6    {
7        public class User
8        {
9            public User()
10            {
11            }
12
13            public int id { get; set; }
14            public string name { get; set; }
15            public DateTime created_at { get; set; }
16        }
17    }

? To create a model class, right-click the Model folder, select the **Add** and **New File** options, and then **Empty Class** option filling in the class name.

Our User model defines an ID for unique identification, user’s name and created date of the user for our users table.

Finally, we will add our database context class. This class reads in the database connection configuration we defined in the Web.config file and takes the Model classes (Datasets) to which it should apply the configuration.

We will create our context class in our Models folder, following the same steps of creating a new empty class, and we will name it ChatContext.cs. In it, we will add the following:

1// File: ChatContext.cs
2
3    using System;
4    using System.Data.Entity;
5    namespace HeyChat.Models
6    {
7        public class ChatContext: DbContext
8        {
9            public ChatContext() : base("YourConnectionName")
10            {
11            }
12
13            public static ChatContext Create()
14            {
15                return new ChatContext();
16            }
17
18            public DbSet<User> Users { get; set; }
19        }
20    }

? We are implementing the Entity Framework ORM using the Code First method. This method involves writing the code defining our models (tables) without any existing database or tables. With this method, the database and tables will be created when our application code is executed.

Logging in Our Users

Since our database connection and model (though as we go along more models may be introduced) have been created, we can proceed with our login functionality.

The front page rendered from the HomeController will consist of a form that accepts a user’s name. This form will be submitted to the /``login route which we defined earlier. Following our route definition, this request will be handled by the AuthController and its Login action method.

We will create the AuthController class and add our code for storing or retrieving a user’s details. The option to either store or retrieve will be based on if the user’s name already exists in our Users Table. The code for the AuthController is below:

1// File: AuthController
2
3    // ...
4    using HeyChat.Models;
5    public class AuthController : Controller
6    {
7        [HttpPost]
8        public ActionResult Login()
9        {
10            string user_name = Request.Form["username"];
11
12            if (user_name.Trim() == "") {
13                return Redirect("/");
14            }
15
16            using (var db = new Models.ChatContext()) {
17
18                User user = db.Users.FirstOrDefault(u => u.name == user_name);
19
20                if (user == null) {
21                    user = new User { name = user_name };
22
23                    db.Users.Add(user);
24                    db.SaveChanges();
25                }
26
27                Session["user"] = user;
28            }
29
30            return Redirect("/chat");
31        }
32    }

In the code above, we check if a user exists using the name. If it exists we retrieve the user’s details and, if it doesn’t, we create a new record first. Then we assign the user’s details into a session object for use throughout the application. Lastly, we redirect the user to the chat page.

Rendering the Chat Page

One feature of most Chat applications is the ability to choose who to chat with. For the purpose of this tutorial, we will assume all registered users can chat with each other so our chat page will offer the possibility of chatting with any of the users stored in our database.

Earlier, we defined our chat route and assigned it to the ChatController class and its Index action method.

Let’s create the ChatController and implement the rendering of the chat page with available contacts. Paste the code below into the ChatController:

1// File: ChatController
2
3    // ...
4    using HeyChat.Models;
5
6    namespace HeyChat.Controllers
7    {
8        public class ChatController : Controller
9        {
10            public ActionResult Index()
11            {
12                if (Session["user"] == null) {
13                    return Redirect("/");
14                }
15
16                var currentUser = (Models.User) Session["user"];
17
18                using ( var db = new Models.ChatContext() ) {
19
20                    ViewBag.allUsers = db.Users.Where(u => u.name != currentUser.name )
21                                     .ToList();
22                }
23
24
25                ViewBag.currentUser = currentUser;
26
27
28                return View ();
29            }
30        }
31    }

To get the available contacts, we read all the users in our database except the current user. These users are passed to our client side using ViewBag. We also pass the current user using ViewBag.

Now that we have retrieved all the available contacts into the ViewBag object, we will create the markup for displaying these contacts and the rest of the chat page to the user. To create the view file for our chat page, we create a Chat folder in the Views folder.

Next, right click the Chat folder, select the options to AddViews, select the Razor template engine and name the file index.cshtml. Paste in the code below into the file:

1<!DOCTYPE html>
2    <html>
3      <head>
4        <title>pChat &mdash; Private Chatroom</title>
5        <link rel="stylesheet" href="@Url.Content("~/Content/app.css")">
6      </head>
7      <body>
8        <!-- Navigation Bar -->
9        <nav class="navbar navbar-inverse">
10          <div class="container-fluid">
11            <div class="navbar-header">
12              <a class="navbar-brand" href="#">pChat - @ViewBag.currentUser.name </a>
13            </div>
14            <ul class="nav navbar-nav navbar-right">
15              <li><a href="#">Log Out</a></li>
16            </ul>
17          </div>
18        </nav>
19        <!-- / Navigation Bar -->
20        <div class="container">
21          <div class="row">
22            <div class="col-xs-12 col-md-3">
23              <aside class="main visible-md visible-lg">
24                <div class="row">
25                  <div class="col-xs-12">
26                    <div class="panel panel-default users__bar">
27                      <div class="panel-heading users__heading">
28                        Contacts (@ViewBag.allUsers.Count)
29                      </div>
30                      <div class="__no__chat__">
31                          <p>Select a contact to chat with</p>
32                      </div>
33                      <div class="panel-body users__body">
34                        <ul id="contacts" class="list-group">
35
36                        @foreach( var user in @ViewBag.allUsers ) {
37                            <a class="user__item contact-@user.id" href="#" data-contact-id="@user.id" data-contact-name="@user.name">
38                                <li>
39                                  <div class="avatar">
40                                     <img src="@Url.Content("~/Content/no_avatar.png")">
41                                  </div>
42                                  <span>@user.name</span>
43                                  <div class="status-bar"></div>
44                                </li>
45                            </a>
46                        }
47                        </ul>
48                      </div>
49                    </div>
50                  </div>
51                </div>
52              </aside>
53
54
55            </div>
56            <div class="col-xs-12 col-md-9 chat__body">
57              <div class="row">
58                <div class="col-xs-12">
59                  <ul class="list-group chat__main">
60
61                  </ul>
62                </div>
63                <div class="chat__type__body">
64                  <div class="chat__type">
65                    <textarea id="msg_box" placeholder="Type your message"></textarea>
66                    <button class="btn btn-primary" id="sendMessage">Send</button>
67                  </div>
68                </div>
69                <div class="chat__typing">
70                  <span id="typerDisplay"></span>
71                </div>
72              </div>
73            </div>
74          </div>
75        </div>
76        <script src="@Url.Content("~/Content/app.js")"></script>
77      </body>
78    </html>

? **@Url.Content("~/Content/app.css")** and **@Url.Content("~/Content/app.js")** load some previously bundled JavaScript and CSS dependencies such as jQuery and Bootstrap from our **Content** folder.

In our view file, we create a sidebar and loop through the users passed to ViewBag to indicate the contacts available using Razor’s @foreach directive. We also add a text area to type and send messages to these contacts.

Selecting Contacts and Sending Messages

When our user selects a contact to chat with, we would like to retrieve the previous messages between the user and the selected contact. In order to achieve this, we would need a table for storing messages between users and a Model for this table.

Let’s create a model called Conversations in the Models folder. It will consist of a unique id, sender_id, receiver_id, message, status and the created_at date. The code for the model is below:

1// File: Conversation.cs
2
3    using System;
4    namespace HeyChat.Models
5    {
6        public class Conversation
7        {
8            public Conversation()
9            {
10                status = messageStatus.Sent;
11            }
12
13            public enum messageStatus
14            {
15                Sent, 
16                Delivered
17            }
18
19            public int id { get; set; }
20            public int sender_id { get; set; }
21            public int receiver_id { get; set; }
22            public string message { get; set; }
23            public messageStatus status { get; set; }
24            public DateTime created_at { get; set; }
25        }
26    }

After creating the Conversation model, we will add it to the ChatContext file as seen below:

1// File: ChatContext.cs
2    using System;
3    using System.Data.Entity;
4
5    namespace HeyChat.Models
6    {
7        public class ChatContext: DbContext
8        {
9            public ChatContext() : base("MySqlConnection")
10            {
11            }
12
13            public static ChatContext Create()
14            {
15                return new ChatContext();
16            }
17
18            public DbSet<User> Users { get; set; }
19            public DbSet<Conversation> Conversations { get; set; }
20        }
21    }

To retrieve the messages, we will create a route for /contact``/conversations/{contact}. This route will accept a contact ID, retrieve messages between the current user and the contact, then return the messages in a JSON response.

It will be handled by the ChatController in the ConversationWithContact action method as seen below:

1//ChatController.cs
2
3    ...
4    public JsonResult ConversationWithContact(int contact)
5    {
6        if (Session["user"] == null)
7        {
8            return Json(new { status = "error", message = "User is not logged in" });
9        }
10
11        var currentUser = (Models.User)Session["user"];
12
13        var conversations = new List<Models.Conversation>();
14
15        using (var db = new Models.ChatContext())
16        {
17            conversations = db.Conversations.
18                              Where(c => (c.receiver_id == currentUser.id 
19                                  && c.sender_id == contact) || 
20                                  (c.receiver_id == contact 
21                                  && c.sender_id == currentUser.id))
22                              .OrderBy(c => c.created_at)
23                              .ToList();
24        }
25
26        return Json(
27            new { status = "success", data = conversations }, 
28            JsonRequestBehavior.AllowGet
29        );
30    }

Now that we have a route to retrieve old messages, we will use some jQuery to select the user, fetch the messages and display them on our page.
In our view file, we will create a script tag to hold our JavaScript and jQuery functions. In it, we’ll add:

1...
2    <script>
3    let currentContact = null; // Holds current contact
4    let newMessageTpl = 
5    `<div>
6        <div id="msg-{{id}}" class="row __chat__par__">
7          <div class="__chat__">
8            <p>{{body}}</p>
9            <p class="delivery-status">Delivered</p>
10          </div>
11        </div>
12     </div>`;
13    ...
14    // select contact to chat with
15    $('.user__item').click( function(e) {
16        e.preventDefault();
17
18        currentContact = {
19            id: $(this).data('contact-id'),
20            name: $(this).data('contact-name'),
21        };
22
23        $('#contacts').find('li').removeClass('active');
24
25        $('#contacts .contact-' + currentContact.id).find('li').addClass('active');
26        getChat(currentContact.id);
27    });
28
29    // get chat data        
30    function getChat( contact_id ) {
31        $.get("/contact/conversations/" + contact_id )
32         .done( function(resp) {         
33            var chat_data = resp.data || [];
34            loadChat( chat_data );         
35         });
36    }
37
38    //load chat data into view
39    function loadChat( chat_data ) {
40
41        chat_data.forEach( function(data) {
42            displayMessage(data);
43        });
44
45        $('.chat__body').show();
46        $('.__no__chat__').hide();
47    }
48
49    function displayMessage( message_obj ) {
50        const msg_id = message_obj.id;
51        const msg_body = message_obj.message;
52
53        let template = $(newMessageTpl).html();
54
55        template = template.replace("{{id}}", msg_id);
56        template = template.replace("{{body}}", msg_body);
57
58        template = $(template);
59
60        if ( message_obj.sender_id == @ViewBag.currentUser.id ) {
61            template.find('.__chat__').addClass('from__chat');
62        } else {
63            template.find('.__chat__').addClass('receive__chat');
64        }
65
66        if ( message_obj.status == 1 ) {
67            template.find('.delivery-status').show();
68        }
69
70        $('.chat__main').append(template);
71    }
72
73Now that selecting a contact retrieves previous messages, we need our user to be able to send new messages. To achieve this, we will create a route that accepts the message being sent and saves it to the database, and then use some jQuery to read the message text from the `textarea` field and send to this route.
74
75``` language-javascript
76    //RouteConfig.cs
77
78    ...
79    routes.MapRoute(
80        name: "SendMessage",
81        url: "send_message",
82        defaults: new { controller = "Chat", action = "SendMessage" }
83    );

As specified in the RouteConfig file, this route will be handled by the SendMessage action method of the ChatController.

1//ChatController.cs
2
3    ...
4    [HttpPost]
5    public JsonResult SendMessage() 
6    {
7        if (Session["user"] == null)
8        {
9            return Json(new { status = "error", message = "User is not logged in" });
10        }
11
12        var currentUser = (User)Session["user"];
13
14        string socket_id = Request.Form["socket_id"];
15
16        Conversation convo = new Conversation
17        {
18            sender_id = currentUser.id,
19            message = Request.Form["message"],
20            receiver_id = Convert.ToInt32(Request.Form["contact"])
21        };
22
23        using ( var db = new Models.ChatContext() ) {
24            db.Conversations.Add(convo);
25            db.SaveChanges();
26        }
27
28        return Json(convo);
29    }

Adding Realtime Functionality

There are several features of a chat application that require realtime functionality, some of which are:
– Receiving messages sent in realtime.
– Being notified of an impending response – the ‘user is typing’ feature.
– Getting message delivery status.
– Instant notification when a contact goes offline or online.

In achieving these features, we will make use of Pusher. To proceed lets head over to the Pusher dashboard and create an app. You can register for free if you haven’t got an account. Fill out the create app form with the information requested. Next, we’ll install the Pusher Server package in our C# code using NuGet.

To achieve some of our stated realtime features, we will need to be able to trigger events on the client side. In order to trigger client events in this application, we will make use of Private Channels.

We will create our private channel when a contact is chosen. This channel will be used to transmit messages between the logged in user and the contact he is sending a message to.

Private channels require an authentication endpoint from our server side code to be available, because when the channel is instantiated Pusher will try to authenticate that the client has valid access to the channel.

The default route for Pusher’s authentication request is /pusher/auth, so we will create this route and implement the authentication.

First in our RouteConfig.cs file we will add the route definition:

1routes.MapRoute(
2        name: "PusherAuth",
3        url:  "pusher/auth",
4        defaults: new { controller = "Auth", action = "AuthForChannel"}
5    );

Then, as we have defined above, in the AuthController class file we will create the AuthForChannel action method and add:

1public JsonResult AuthForChannel(string channel_name, string socket_id)
2    {
3        if (Session["user"] == null)
4        {
5            return Json(new { status = "error", message = "User is not logged in" });
6        }
7        var currentUser = (Models.User)Session["user"];
8
9        var options = new PusherOptions();
10        options.Cluster = "PUSHER_APP_CLUSTER";
11
12        var pusher = new Pusher(
13        "PUSHER_APP_ID",
14        "PUSHER_APP_KEY",
15        "PUSHER_APP_SECRET", options);
16
17        if (channel_name.IndexOf(currentUser.id.ToString()) == -1)
18        {
19            return Json(
20              new { status = "error", message = "User cannot join channel" }
21            );
22        }
23
24        var auth = pusher.Authenticate(channel_name, socket_id);
25
26        return Json(auth);
27    }

Our authentication endpoint, above, takes the name of the channel and the socket ID of the client, which are sent by Pusher at a connection attempt.

? We will name our private channels using the IDs of the participants of the conversation i.e. the sender and receiver. This we will use to restrict the message from being broadcast to other users of the Messenger app that are not in the specific conversation.

Using the .NET PusherServer library, we authenticate the user by passing the channel name and socket ID. Then we return the resulting object from authentication via JSON.

For more information on client events and private channels, kindly check out the Pusher documentation.

? Client events can only be triggered by private or presence channels.

In the script section of our view, we will instantiate the variable for our private channel. We will also adjust our contact selecting snippet to also create the channel for sending messages, typing and delivery notifications:

1...
2    <script>
3    ...
4
5    let currentContact = null; // Holds contact currently being chatted with
6    let socketId = null;
7    let currentconversationChannel = null;
8    let conversationChannelName = null;
9
10    //Pusher client side setup
11    const pusher = new Pusher('PUSHER_APP_ID', {
12        cluster:'PUSHER_APP_CLUSTER'
13    });
14
15    pusher.connection.bind('connected', function() {
16      socketId = pusher.connection.socket_id;
17    });
18
19    // select contact to chat with
20    $('.user__item').click( function(e) {
21        e.preventDefault();
22
23        currentContact = {
24            id: $(this).data('contact-id'),
25            name: $(this).data('contact-name'),
26        };
27
28        if ( conversationChannelName ) {
29            pusher.unsubscribe( conversationChannelName );
30        }
31
32        conversationChannelName = getConvoChannel( 
33                                      (@ViewBag.currentUser.id * 1) ,  
34                                      (currentContact.id * 1) 
35                                  );
36
37        currentconversationChannel = pusher.subscribe(conversationChannelName);
38
39        bind_client_events();
40
41        $('#contacts').find('li').removeClass('active');
42
43        $('#contacts .contact-' + currentContact.id).find('li').addClass('active');
44        getChat(currentContact.id);
45    });
46
47    function getConvoChannel(user_id, contact_id) {
48        if ( user_id > contact_id ) {
49            return 'private-chat-' + contact_id + '-' + user_id;
50        }
51
52        return 'private-chat-' + user_id + '-' + contact_id;
53    }
54
55    function bind_client_events(){
56      //bind private channel events here  
57
58      currentconversationChannel.bind("new_message", function(msg) {
59          //add code here
60      });
61
62      currentconversationChannel.bind("message_delivered", function(msg) {
63          $('#msg-' + msg.id).find('.delivery-status').show();
64      });
65    }

We have also saved the socket_id used to connect to the channel in a variable. This will come in handy later.

Receiving Messages Sent in Realtime
Earlier, we added a route to save messages sent as conversations between the user and a contact.

However, after these messages are saved, we would like the messages to be added to the screen of both the user and contact.

For this to work, in our C# code, after storing the message we will trigger an event via our Pusher private channel. Our clients will then listen to these events and respond to them by adding the messages they carry to the screen.

In our ChatController class file, after saving the conversation we will add the following:

1private Pusher pusher;
2
3    //class constructor
4    public ChatController() 
5    {
6        var options = new PusherOptions();
7        options.Cluster = "PUSHER_APP_CLUSTER";
8
9        pusher = new Pusher(
10           "PUSHER_APP_ID",
11           "PUSHER_APP_KEY",
12           "PUSHER_APP_SECRET",
13           options
14       );
15    }
16
17    [HttpPost]
18    public JsonResult SendMessage() 
19    {
20        if (Session["user"] == null)
21        {
22            return Json(new { status = "error", message = "User is not logged in" });
23        }
24
25        var currentUser = (User)Session["user"];
26
27        string socket_id = Request.Form["socket_id"];
28
29        Conversation convo = new Conversation
30        {
31            sender_id = currentUser.id,
32            message = Request.Form["message"],
33            receiver_id = Convert.ToInt32(Request.Form["contact"])
34        };
35
36        using ( var db = new Models.ChatContext() ) {
37            db.Conversations.Add(convo);
38            db.SaveChanges();
39        }
40
41        var conversationChannel = getConvoChannel( currentUser.id, contact);
42
43        pusher.TriggerAsync(
44          conversationChannel,
45          "new_message",
46          convo,
47          new TriggerOptions() { SocketId = socket_id });
48
49        return Json(convo);
50    }
51
52    private String getConvoChannel(int user_id, int contact_id)
53    {
54        if (user_id > contact_id)
55        {
56            return "private-chat-" + contact_id + "-" + user_id;
57        }
58
59        return "private-chat-" + user_id + "-" + contact_id;
60    }

To make use of the Pusher server-side functionality, we will add using PusherServer; to the top of our controller file.

? We have accepted the socket_id from the user when sending the message. This is so that we can specify that the sender is exempted from listening to the event they broadcast.

In our view, we will listen to the new_message event and use this to add the new message to our view.

1//index.cshtml
2
3    ...
4    <script>
5    ...
6    //Send button's click event
7    $('#sendMessage').click( function() {
8        $.post("/send_message", {
9            message: $('#msg_box').val(),
10            contact: currentContact.id,
11            socket_id: socketId,
12        }).done( function (data) {
13            //display the message immediately on the view of the sender
14            displayMessage(data); 
15            $('#msg_box').val('');
16        });
17    });
18
19    function bind_client_events(){
20        //listening to the message_sent event by the message's recipient
21        currentconversationChannel.bind("new_message", function(msg) {
22                if ( msg.receiver_id == @ViewBag.currentUser.id ) {
23                    displayMessage(msg);
24                }
25        });
26    }

Implementing the ‘user Is Typing’ Feature
This feature makes users aware that the conversation is active and a response is being typed. To achieve it, we will listen to the keyup event of our message text area and, upon the occurrence of this keyup event, we will trigger a client event called client-is-typing.

1// index.cshtml
2
3    function bind_client_events(){
4        currentconversationChannel.bind("client-is-typing", function(data) {
5            if ( data.user_id == currentContact.id && 
6                 data.contact_id == @ViewBag.currentUser.id  ) {
7
8                $('#typerDisplay').text( currentContact.name + ' is typing...');
9
10                $('.chat__typing').fadeIn(100, function() {
11                    $('.chat__type__body').addClass('typing_display__open');
12                }).delay(1000).fadeOut(300, function(){
13                    $('.chat__type__body').removeClass('typing_display__open');
14                });
15            }
16        });
17
18        ...
19    }
20
21    //User is typing
22    var isTypingCallback = function() {
23        chatChannel.trigger("client-is-typing", {
24            user_id: @ViewBag.currentUser.id,
25            contact_id: currentContact.id,
26        });
27    };
28
29    $('#msg_box').on('keyup',isTypingCallback);
30    ...

Conclusion

We have built a chat application with some of its basic features in C# with the help of jQuery, and have also implemented some of the common realtime features present in chat applications using Pusher. This is just a small portion of what building C# applications with the help of Pusher’s realtime functionality has to offer.

We would love to hear your thoughts and take on building applications with C# and Pusher. If you have any questions on segments of this tutorial, we would love to hear those too. So please, leave a comment below! The entire code from this tutorial is available on Github.