Home > .Net, .Net 3.0 / 3.5, ASP.Net, Javascript > A Simple Chat script using ASP.Net C#

A Simple Chat script using ASP.Net C#

September 11th, 2009 Anuraj P Leave a comment Go to comments

Few days back one of my colleague was looking for a simple chat script in ASP.Net, but he can’t found one. Almost all of the chat scripts were in ASP and he want to do it for an internal site. So I thought about implementing one. And here is the simple script using ASP.Net’s Page method feature. For this I am using Windows Authentication, because it is for a intranet site, where users will be coming from one domain only.

Code behind – Global.asax

private List<string> onlineUsers;
void Session_Start(object sender, EventArgs e)
{
	if (this.onlineUsers == null)
	{
            this.onlineUsers = new List</string><string>();
        }

        if (!this.onlineUsers.Contains(HttpContext.Current.User.Identity.Name))
        {
            this.onlineUsers.Add(HttpContext.Current.User.Identity.Name);
        }
        HttpContext.Current.Session["Users"] = this.onlineUsers;
}

void Session_End(object sender, EventArgs e)
{
        if (this.onlineUsers != null)
        {
            this.onlineUsers.Remove(HttpContext.Current.User.Identity.Name);
        }
	HttpContext.Current.Session["Users"] = this.onlineUsers;
}

Web.Config

<authentication mode="Windows"/>
<authorization>
	<deny users="?"/>
</authorization>

Default.aspx.cs

private static List</string><string> chatCollection;

[WebMethod(true)]
public static List</string><string> Add(string comment)
{
	string user = HttpContext.Current.User.Identity.Name;
        if (chatCollection == null)
        {
		chatCollection = new List</string><string>();
        }
        comment = comment.Replace("< ", "[").Replace(">", "]");
        comment = GetSmileys(comment);
        chatCollection.Add(string.Format("<tr><td>{0} :<font color=\"blue\">{1}</font></td></tr>", user, comment));
        return chatCollection;
}

private static string GetSmileys(string comment)
{
        if (comment.Contains("[:-)]"))
        {
        	comment = comment.Replace("[:-)]", "<img src=\"icons\\smile.gif\"/>");
        }
        else if (comment.Contains("[;-)]"))
        {
        	comment = comment.Replace("[;-)]", "<img src=\"icons\\wink.gif\"/>");
        }
        else if (comment.Contains("[:-(]"))
        {
        	comment = comment.Replace("[:-(]", "<img src=\"icons\\frown.gif\"/>");
        }
        else if (comment.Contains("[:-D]"))
        {
        	comment = comment.Replace("[:-D]", "<img src=\"icons\\biggrin.gif\"/>");
        }
        else if (comment.Contains("[:-|]"))
        {
        	comment = comment.Replace("[:-|]", "<img src=\"icons\\blankstare.gif\"/>");
        }
        else if (comment.Contains("[B-)]"))
        {
        	comment = comment.Replace("[B-)]", "<img src=\"icons\\cool.gif\"/>");
        }
        else if (comment.Contains("[}-)]"))
        {
        	comment = comment.Replace("[}-)]", "<img src=\"icons\\devilish.gif\"/>");
        }
        else if (comment.Contains("[:-P]"))
        {
        	comment = comment.Replace("[:-P]", "<img src=\"icons\\p.gif\"/>");
        }
	return comment;
}

[WebMethod(true)]
public static List</string><string> GetChat()
{
	if (chatCollection == null)
        {
        	chatCollection = new List</string><string>();
        }
        return chatCollection;
}

[WebMethod(true)]
public static List</string><string> GetUsers()
{
	if (HttpContext.Current.Session["Users"] == null)
        {
        	HttpContext.Current.Session["Users"] = new List</string><string>();
        }
        return HttpContext.Current.Session["Users"] as List</string><string>;
}

And finally the HTML

Default.aspx


< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>:: TEAM CHAT ::</title>

    <script type="text/javascript">
        function sendChat() {
            var chatText = $get("txtChatInput").value;
            if (chatText != "") {
                PageMethods.Add(chatText, sendChat_Callback);
            }
            else {
                $get("txtChatInput").focus();
            }
            return false;
        }
        function sendChat_Callback(response) {
            displayChatText(response);
            $get("txtChatInput").value = "";
            $get("txtChatInput").focus();
        }
        function GetChat() {
            PageMethods.GetChat(GetChat_Callback);
        }
        function GetChat_Callback(response) {
            displayChatText(response);
        }
        function displayChatText(response) {
            var result;
            result = "<table>";
            for (var i = response.length - 1; i >= 0; i--) {
                result = result + response[i];
            }
            result = result + "</table>";
            $get("chatOutputDiv").innerHTML = result;
        }
        function getUsers() {
            PageMethods.GetUsers(GetUsers_Callback);
        }
        function GetUsers_Callback(response) {
            $get("lstUsers").options.length = 0;
            for (var i = response.length - 1; i >= 0; i--) {
                addUsers(response[i]);
            }
        }
        function addUsers(text) {
            var optn = document.createElement("OPTION");
            optn.text = text;
            optn.value = text;
            $get("lstUsers").options.add(optn);
        }
        function LoadUI() {
            getUsers();
            GetChat();
            $get("txtChatInput").focus();
        }
        function showAbout() {
            var msg = "Copyright (c) 2009 Anuraj. All rights reserved.\nLicenced under GNU GPL v2.";
            msg += "\n\nVersion 0.2 : Supports Smileys\n";
            msg += "Smileys should be in square brackets, like below,\ncase-sensitive(Sorry I will fix it later)\n";
            msg += "Supported :- [:-)], [;-)], [:-(], [:-D], [:-|], [B-)], [}-)],[:-P]\n";
            msg += "\n\nHappy Chatting [:)]\n";
            alert(msg);
        }
        setInterval("LoadUI();", 5000);
    </script>

    <style type="text/css">
        body
        {
            font-family: Calibri;
            font-size: 11pt;
        }
        input
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        .txt
        {
            border: solid 1px #000;
            font-family: Calibri;
            font-size: 11pt;
            color: Black;
        }
        option
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        h1
        {
            color: Blue;
            font-size: xx-large;
            text-decoration: underline;
            text-align: center;
        }
    </style>
</head>
<body onload="javascript:LoadUI();">
    <form id="form1" runat="server" onsubmit="javascript:return sendChat();">
    <div>
        <asp :ScriptManager runat="server" ID="scriptMgr" EnablePageMethods="true" ScriptMode="Release"
            EnableViewState="false" />
        <table cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td colspan="2" style="text-align: center">
                    <h1>
                        :: TEAM CHAT ::
                    </h1>
                    <span>A simple chat script using ASP.Net and C#</span>
                    &nbsp;<a href="javascript:void('About');" title="About TeamChat" onclick="javascript:return showAbout

();">?</a>&nbsp;
                </td>
            </tr>
            <tr>
                <td>

                    <input class="txt" type="text" maxlength="1500" style="width: 340px;" id="txtChatInput" />
                </td>
                <td valign="middle">
                    &nbsp;<input type="button" id="cmdSubmit" value="Send" onclick="javascript:return sendChat();" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <div id="chatOutput" style="height: 300px; width: 400px; border: solid 1px #000;
                        overflow: scroll;">
                        <div id="chatOutputDiv" style="height: 280px; width: 380px;">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <label>
                        Online Users</label><br />
                    <select class="txt" size="4" id="lstUsers" style="width: 400px; border: thin solid #000000;
                        font-family: Calibri; font-size: 11pt; color: #FFFFFF;">
                        <option>No users available </option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center; font-size: 11px;">
                    Copyright &copy; 2009 <a href="mailto:anuraj.p@mymailserver.com">Anuraj</a>. All rights
                    reserved.<br />
                    Licenced under GNU GPL v2.
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Here is the Image “Team Chat” running on my machine

Team chat - asp.net script screenshot

Team chat - asp.net script screenshot

Code seems like pretty self explantory. As wordpress don’t support zip attachments, I will upload, and give the source later.

Happy Chating ;)

I took the Emoticons from deviantart.com

  1. October 1st, 2009 at 05:37 | #1

    I don’t know If I said it already but …Cool site, love the info. I do a lot of research online on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks, :)

    A definite great read..Jim Bean

  2. October 1st, 2009 at 14:37 | #2

    Thanks JimmyBean.

  1. No trackbacks yet.