Archive

Posts Tagged ‘ASP.Net Chat script’

A Simple Chat script using ASP.Net C#

September 11th, 2009 Anuraj P 2 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

Set timeout and Clear timeout in Javascript

May 16th, 2007 Anuraj P No comments

Timing events in javascript helps to execute a function, after a specified time interval.

setTimeout() – Executes a code some time in the future.
clearTimeout() – Cancel an existing setTimeout event.

var somevariable = setTimeout("function_to_execute",milliseconds);
clearTimeout(somevariable)

Here is sample code snippet for a Javascript counter using SetTimeout and ClearTimeout functions.

Timing events in javascript helps to execute a function, after a specified time interval.

setTimeout() – Executes a code some time in the future.
var somevariable = setTimeout(“function_to_execute”,milliseconds);

clearTimeout() – Cancel an existing setTimeout event.
clearTimeout(somevariable)

Code of a javascript counter.

<html>
<head>
    <title>Javascript counter</title>

    <script type="text/javascript" language="Javascript">
        var var_counter = 0;
        var var_timer;
        function start_counter() {
            document.getElementById("counter").innerText = var_counter;
            var_counter++; var_timer = setTimeout("start_counter()", 1000);
        }
        function stop_counter() {
            clearTimeout(var_timer);
        }
    </script>
</head>
<body>
    Counter :
    <div id="counter">
    </div>
    <br />
    <button onclick="start_counter()">
        Start</button>
    <button onclick="stop_counter()">
        Stop</button>
</body>
</html>

if var_counter variable is local scope instead of global, every time clicking on start button will initialize the counter.

There is two more timing related functions available in Javascript.

SetInterval() and ClearInterval() – It is almost same as the SetTimeout and clearTimeout, only difference is setTimeout() triggers expression only once, setInterval() keeps triggering expression again and again (unless you tell it to stop). And the Syntax are same. You can write the counter with SetInterval very easily that setTimeOut