DEV Community

Chimezie Enyinnaya
Chimezie Enyinnaya

Posted on

How to build a public anonymous chat app using .NET and Pusher

Anonymity gives the likelihood to wear a cover, to end up being anyone you need to be. Also, anonymous communication permits you to quit being bashful and act naturally. It is a chance to pull in individuals whom you won't have the confidence to get to know, all things considered.

Today, we will create a real-time public anonymous group chat app using C# ASP.NET and Pusher. This tutorial assumes the reader has basic knowledge of C# ASP.NET.

Setting Up Pusher App

We need to sign up on Pusher and create a new app, and also copy our secret, application key and application id.

Setting Up The Asp.Net Project In Visual Studio

We need to create a new Asp.Net MVC application, so we open up Visual Studio, select new project from the sidebar, under templates, select Visual C#, next, select web, and finally in the middle section, select ASP.NET Web Application.

Now we are almost ready. The next step will be to install the official Pusher library for .Net using the NuGet Package. To do this, we go to tools on the top bar, click on NuGet Package Manager, on the dropdown we select Package Manager Console. After doing this, we will see the Package Manager Console at the bottom of our Visual Studio as shown below.

The next step is to install the library, by running the following command in the console.

    Install-Package PusherServer
Enter fullscreen mode Exit fullscreen mode

Once this is done, our environment has now been set up.

Crafting The Chat Application

Now that our environment is set up and ready, let us dive into writing some code.
By default, Visual Studio creates three controllers for us, however we will be using the HomeController for the logic of our chat application.
The first thing we want to do is to delete the default index.cshtml file under the Views/Home folder, and create a new view file named index.cshtml that does not have a master layout. In our new index.cshtml file, let us copy the following contents into it.

    @{
        Layout = null;
        Response.ContentType = "text/HTML";
    }
    <html>
    <head>
        <title>
            Pusher Tutorial
        </title>
    </head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="//js.pusher.com/4.0/pusher.min.js"></script>
    <style>
        .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;
        }
    </style>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            <span class="glyphicon glyphicon-comment"></span> Chat
                        </div>
                        <div class="panel-body">
                            <ul class="chat" id="chat"></ul>
                        </div>
                        <div class="panel-footer">
                            <div class="input-group">
                                <input id="btn-input" class="form-control input-sm" placeholder="Type your message here..." type="text">
                                <span class="input-group-btn">
                                    <button class="btn btn-warning btn-sm" id="btn-chat">
                                        Send
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>    
    </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

In the above piece of code, we have defined the layout to be null, and we have defined the content type as "text/HTML" so Asp.Net does not attempt to parse the page as XML. We required Bootstrap CSS, jQuery library, as well as the Pusher JavaScript library, before defining the HTML structure. If we save our file and run our project, we should see this.

Now we have to trigger an event when someone enters some text and clicks the send button. Let's open up our index.cshtml file again and add the following at the end of the page.

    <script>
        $(document).ready(function(){
            $("#btn-chat").click(function(){
                var message = $('#btn-input').val();

                $.post({
                    url: '@Url.Action("Pushermessage", "Home")',
                    dataType: 'text/HTML',
                    contentType: "application/json",
                    data: JSON.stringify({
                        "message": message
                    }),
                    success: function (data) {
                        $("#btn-input").val('');
                    }
                });
            })
        })
    </script>
Enter fullscreen mode Exit fullscreen mode

In the above code, we have attached a click event listener to the element with the ID of btn-chat which happens to be our button. Once the button is clicked, the code will take the value of the element with the id of btn-input which happens to be our text box, and send an AJAX call to our Pushermessage function in our HomeController. However, we are yet to create the Pushermessage function that responds to the AJAX call.

Let us move to our HomeController, and paste the following code after the index function.

     [HttpPost]
            public async Task<ActionResult> Pushermessage(String message)
            {
                var options = new PusherOptions();
                options.Cluster = "XXX_CLUSTER";
                var pusher = new Pusher("XXX_APP_ID", "XXX_APP_KEY", "XXX_APP_SECRET", options);
                ITriggerResult result = await pusher.TriggerAsync("asp_channel", "asp_event", new { message = message, name = "Anonymous" });

                return new HttpStatusCodeResult((int)HttpStatusCode.OK);

            } 
Enter fullscreen mode Exit fullscreen mode

Don't forget to add the following references to the top of your file, before the class declaration

    using PusherServer;
    using System.Net;
    using System.Threading.Tasks;
Enter fullscreen mode Exit fullscreen mode

In the last two block of codes, we have defined our Pushermessage function and we also decorated it with the [HttpPost] decorator, so Asp.Net knows it’s a function for POST requests. In this function, we instantiate Pusher, using our appId, appKey and appSecret respectively. We then went ahead to trigger a channel called asp_channel and an event called asp_event, sending in two values with it.

At this point, if we reload our app, type in a message and send, we should see the following when we visit our debug console on our Pusher dashboard:

At this point, we are done with emitting the message to data. Let us now move onto listening for the event on the client side and displaying the new message.

Let us open up our index.cshtml file, and add the following lines of code after our click event.

    var pusher = new Pusher('PUSHER_APP_KEY', {cluster: 'XXX_CLUSTER'});
    var my_channel = pusher.subscribe('asp_channel');
    my_channel.bind("asp_event", function (data) {
        var new_message = '<li class="left clearfix"><span class="chat-img pull-left">';
        new_message +='<img src="http://placehold.it/50/55C1E7/fff&text='+data.name+'" alt="User Avatar" class="img-circle">';
        new_message +=  '</span>';
        new_message +=      '<div class="chat-body clearfix">';
        new_message +=          '<div class="header">';
        new_message +=               '<strong class="primary-font">'+data.name+'</strong> <small class="pull-right text-muted">';
        new_message +=                  '</div>';
        new_message +=                      '<p>';
        new_message +=  data.message;
        new_message +=                      '</p>';
        new_message +=                   '</div>';
        new_message +=      '</li>';
    $("#chat").append(new_message);
    });
Enter fullscreen mode Exit fullscreen mode

In the above block of code, we declared a variable called pusher and we set it to an instance of a new Pusher object, passing in our appKey. Next, we declared a variable called my_channel, and we call the Pusher subscribe method to our channel, which in this case, is called asp_channel.

Next, we bind to the event, receive the data passed from it, wrap the data in some li tags, and then we append it to the ul element in our HTML structure with the ID of chat. Below is our functionality:

In this article, we have demonstrated how to create a public anonymous chat application using C# ASP.NET and Pusher. We have gone over the process of setting up the environment, using the NuGet Package Console to install packages as well as implementing the chat application.

Many other real-time applications can be built using Pusher and ASP.NET, it's left for you to decide which awesome realtime app you'll be building next.

This post was originally posted by the author on the Pusher blog.

Top comments (0)