0 Replies - 949 Views - Last Post: 25 April 2012 - 07:30 AM Rate Topic: -----

#1 Kannibal   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 18-December 09

ASP.NET Ajax Chat Problem

Posted 25 April 2012 - 07:30 AM

Hello Members
i am currently trying to make a simple multi user chat room using asp.net and ajax with timers the users can log into a room but they are not able to send any messages since once i click the send button the text does not display my code can be found below.

I have been following a tutorial in order to make this chat room since it is my first time coding something like this the tutorial link is the following http://www.codeproje...ET-2-0-and-AJAX i did not link the default.aspx since that works fine and the user can be able to enter a chatroom

ChatEngine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Web;
using System.Text;
using System.Configuration;
using System.Collections;

namespace GameBL
{
    public static class ChatEngine
    {
        #region Members
        private static Dictionary<string, ChatRoom> Rooms = new Dictionary<string, ChatRoom>(Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["MaxChatRooms"]));
        private static int userChatRoomSessionTimeout = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["UserChatRoomSessionTimeout"]);
        #endregion

        #region Methods
        /// <summary>
        /// Cleans all the chat roomsDeletes the empty chat rooms
        /// </summary>
        /// <param name="state"></param>
        public static void CleanChatRooms(object state)
        {
            lock (Rooms)
            {
                foreach (object key in Rooms.Keys)
                {
                    ChatRoom room = Rooms[key.ToString()];
                    room.ExpireUsers(userChatRoomSessionTimeout);
                    if (room.IsEmpty())
                    {
                        room.Dispose();
                        Rooms.Remove(key.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// Returns the chat room for this two users or create a new one if nothing exists
        /// </summary>
        /// <param name="user1ID"></param>
        /// <param name="user2ID"></param>
        /// <returns></returns>
        public static ChatRoom GetRoom(string roomID)
        {
            ChatRoom room = null;
            lock (Rooms)
            {
                if (Rooms.ContainsKey(roomID))
                    room = Rooms[roomID];
                else
                {
                    room = new ChatRoom(roomID);
                    Rooms.Add(roomID, room);
                }
            }
            return room;
        }

        /// <summary>
        /// Deletes the specified room
        /// </summary>
        /// <param name="roomID"></param>
        public static void DeleteRoom(string roomID)
        {
            if (!Rooms.ContainsKey(roomID))
                return;
            lock (Rooms)
            {
                ChatRoom room = Rooms[roomID];
                room.Dispose();
                Rooms.Remove(roomID);
            }
        }


        #endregion
    }
}



ChatMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameBL
{
    public class Message
    {
        #region Members
        public string user;
        public string msg;
        public MsgType type;
        #endregion

        #region Constructors
        public Message(string _user, string _msg, MsgType _type)
        {
            user = _user;
            msg = _msg;
            type = _type;
        }
        public Message(string _user, MsgType _type) : this(_user, "", _type) { }
        public Message(MsgType _type) : this("", "", _type) { }
        #endregion

        #region Methods
        public override string ToString()
        {
            switch (this.type)
            {
                case MsgType.Msg:
                    return this.user + " says: " + this.msg;
                case MsgType.Join:
                    return this.user + " has joined the room";
                case MsgType.Left:
                    return this.user + " has left the room";
            }
            return "";
        }
        #endregion
    }
    public enum MsgType { Msg, Start, Join, Left, Action }
}



ChatRoom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace GameBL
{
    public class ChatRoom : IDisposable
    {
        #region Members

        public List<Message> messages = null;
        public string RoomID;
        private Dictionary<string, ChatUser> RoomUsers;
        private int userChatRoomSessionTimeout;

        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            this.messages.Clear();
            this.RoomID = "";
            foreach (object key in RoomUsers.Keys)
            {
                this.RoomUsers[key.ToString()].Dispose();
            }


        }

        #endregion

        #region Constructors
        public ChatRoom(string roomID)
        {
            this.messages = new List<Message>();
            this.RoomID = roomID;
            userChatRoomSessionTimeout = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["UserChatRoomSessionTimeout"]);
            RoomUsers = new Dictionary<string, ChatUser>(Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["ChatRoomMaxUsers"]));
        }
        #endregion

        #region Methods
        /// <summary>
        /// Returns the user with the specified id
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ChatUser GetUser(string userID)
        {
            if (!this.RoomUsers.ContainsKey(userID))
                return null;
            return this.RoomUsers[userID];
        }


        /// <summary>
        /// Determines if the room is empty or not
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            lock (this)
            {
                foreach (object key in RoomUsers.Keys)
                {
                    if (this.RoomUsers[key.ToString()].IsActive == true)
                        return false;
                }
                return true;
            }
        }


        #region Operations Join,Send,Leave
        /// <summary>
        /// Marks the user as inactive
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public void LeaveRoom(string userID)
        {
            //deactivate user 
            ChatUser user = this.GetUser(userID);
            if (user == null)
                return;
            user.IsActive = false;
            user.LastSeen = DateTime.Now;
            this.RoomUsers.Remove(userID);

            //Add leaving message
            Message msg = new Message(user.UserName, "", MsgType.Left);
            this.AddMsg(msg);

            if (IsEmpty())
                ChatEngine.DeleteRoom(this.RoomID);

        }


        /// <summary>
        /// Activates the user and adds a join message to the room
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="userName"></param>
        /// <returns>All the messages sent in the room</returns>
        public string JoinRoom(string userID, string userName)
        {

            //activate user 
            ChatUser user = new ChatUser(userID, userName);
            user.IsActive = true;
            user.UserName = userName;
            user.LastSeen = DateTime.Now;
            if (!this.RoomUsers.ContainsKey(userID))
            {
                //Add join message
                Message msg = new Message(user.UserName, "", MsgType.Join);
                this.AddMsg(msg);
                //Get all the messages to the user
                int lastMsgID;
                List<Message> previousMessages = this.GetMessagesSince(-1, out lastMsgID);
                user.LastMessageReceived = lastMsgID;
                //return the messages to the user
                string str = GenerateMessagesString(previousMessages);
                this.RoomUsers.Add(userID, user);
                return str;
            }
            return "";
        }


        /// <summary>
        /// Adds a message in the room
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="senderID"></param>
        /// <returns>All the messages sent from the other user from the last time the user sent a message</returns>
        public string SendMessage(string strMsg, string senderID)
        {
            ChatUser user = this.GetUser(senderID);
            Message msg = new Message(user.UserName, strMsg, MsgType.Msg);
            user.LastSeen = DateTime.Now;
            this.ExpireUsers(userChatRoomSessionTimeout);
            this.AddMsg(msg);
            int lastMsgID;
            List<Message> previousMsgs = this.GetMessagesSince(user.LastMessageReceived, out lastMsgID);
            if (lastMsgID != -1)
                user.LastMessageReceived = lastMsgID;
            string res = this.GenerateMessagesString(previousMsgs);
            return res;
        }

        #endregion

        /// <summary>
        /// Removes the users that hasn't sent any message during the last window secondes 
        /// </summary>
        /// <param name="window">time in secondes</param>
        public void ExpireUsers(int window)
        {
            lock (this)
            {
                foreach (object key in RoomUsers.Keys)
                {
                    ChatUser usr = this.RoomUsers[key.ToString()];
                    lock (usr)
                    {
                        if (usr.LastSeen != System.DateTime.MinValue)
                        {
                            TimeSpan span = DateTime.Now - usr.LastSeen;
                            if (span.TotalSeconds > window && usr.IsActive != false)
                            {
                                this.LeaveRoom(usr.UserID);
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// Adds a message to the room
        /// <param name="msg"></param>
        /// <returns> the id of the new message</returns>
        public int AddMsg(Message msg)
        {
            int count;
            lock (messages)
            {
                count = messages.Count;
                messages.Add(msg);
            }
            return count;
        }



        /// <summary>
        /// Iterates over the messages array calling ToString() for each message
        /// </summary>
        /// <param name="msgs"></param>
        /// <returns></returns>
        private string GenerateMessagesString(List<Message> msgs)
        {
            string res = "";
            for (int i = 0; i < msgs.Count; i++)
            {
                res += ((Message)msgs[i]).ToString() + "\n";
            }
            return res;
        }


        /// <summary>
        /// Returns an array that contains all messages sent after the message with id=msgid
        /// </summary>
        /// <param name="msgid">The id of the message after which all the message will be retuned </param>
        /// <param name="lastMsgID">the id of the last message returned</param>
        /// <returns></returns>
        public List<Message> GetMessagesSince(int msgid, out int lastMsgID)
        {
            lock (messages)
            {
                if ((messages.Count) <= (msgid + 1))
                    lastMsgID = -1;
                else
                    lastMsgID = messages.Count - 1;
                return messages.GetRange(msgid + 1, messages.Count - (msgid + 1));
            }
        }


        /// <summary>
        /// Returns all the messages sent since the last message the user received
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public string UpdateUser(string userID)
        {
            ChatUser user = this.GetUser(userID);
            user.LastSeen = DateTime.Now;
            this.ExpireUsers(userChatRoomSessionTimeout);
            int lastMsgID;
            List<Message> previousMsgs = this.GetMessagesSince(user.LastMessageReceived, out lastMsgID);
            if (lastMsgID != -1)
                user.LastMessageReceived = lastMsgID;
            string res = this.GenerateMessagesString(previousMsgs);
            return res;
        }



        /// <summary>
        /// Returns the names of the users who aer currently in the rooms
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> GetRoomUsersNames()
        {
            ExpireUsers(userChatRoomSessionTimeout);
            foreach (object key in RoomUsers.Keys)
            {
                yield return this.RoomUsers[key.ToString()].UserName;
            }

        }

        #endregion
    }
}



ChatUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameBL
{
    public class ChatUser : IDisposable
    {
        #region Members
        public string UserID;
        public string UserName;
        public bool IsActive;
        public DateTime LastSeen;
        public int LastMessageReceived;
        #endregion

        #region Constructors
        public ChatUser(string id, string userName)
        {
            this.UserID = id;
            this.IsActive = false;
            this.LastSeen = DateTime.MinValue;
            this.UserName = userName;
            this.LastMessageReceived = 0;
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            this.UserID = "";
            this.IsActive = false;
            this.LastSeen = DateTime.MinValue;
            this.UserName = "";
            this.LastMessageReceived = 0;
        }
        #endregion
    }
}



Scripts.js
// JScript File
        	var msgTimer = "";
        	var membersTimer = "";
			
			startTimers();
	      
			function startTimers()
			{
				msgTimer = window.setInterval("updateUser()",3000);
				membersTimer = window.setInterval("updateMembers()",10000);
			} 
			function stopTimers()
			{
				window.clearInterval (msgTimer);
				window.clearInterval (membersTimer);
				msgTimer="";
				membersTimer="";
			}
			function updateUser()
			{
			    PageMethods.UpdateUser($get("hdnRoomID").value, UpdateMessages);
			}
			function updateMembers()
			{
			    PageMethods.UpdateRoomMembers($get("hdnRoomID").value, UpdateMembersList);
			}
			function Leave()
			{
			    stopTimers();
			    PageMethods.LeaveRoom($get("hdnRoomID").value);
			}
			function button_clicked()
			{
				PageMethods.SendMessage($get("txtMsg").value,$get("hdnRoomID").value,UpdateMessages, errorCallback);
				$get("txtMsg").value="";
				$get("txt").scrollIntoView("true");
			}
			function clickButton(e, buttonid)
			{ 
				var bt = document.getElementById(buttonid); 
				if (typeof bt == 'object')
					{ 
						if(navigator.appName.indexOf("Netscape")>(-1))
						{ 
						    if (e.keyCode == 13)
						    { 
							    bt.click(); 
							    return false; 
						    } 
					    } 
				    if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
					    { 
						    if (event.keyCode == 13)
						    { 
						        bt.click(); 
							    return false; 
						    } 
					    } 
				    }	 
			} 
			
			function UpdateMessages(result)
			{
			    $get("txt").value=$get("txt").value+result;
			    $get("txt").doScroll();
			}
			function UpdateMembersList(result)
			{
			   // alert(result);
			    var users=result.split(",");
			   // alert(users.length);
			    var i=0;
                
                
                $get("lstMembers").options.length=0;
                 var i=0;
                while (i < users.length)
                {
                    if (users[i]!="");
                    {
                        var op=new Option(users[i],users[i]);
                        $get("lstMembers").options[$get("lstMembers").options.length]= op;
                    }
                    i+=1;
                }
                
			    //$get("lstMembers").value=$get("txt").value+result;
			    //$get("txt").doScroll();
			}
			function errorCallback(result)
			{
				alert("An error occurred while invoking the remote method: " 
				+ result);
			}
			
        



Chat.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Chat.aspx.cs" Inherits="GameWebsite.Chat" %>
<asp:Content ID="Content1" ContentPlaceHolderID="text" runat="server">
<div id="tabs">
        <ul>
            <li><a href="#tabs-1">Chatroom</a></li>
	    </ul>
	    <div id="tabs-1">
    <input id="hdnRoomID" type="hidden" name="hdnRoomID" runat="server"/>

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" EnablePageMethods="True">
        <scripts>
                <asp:ScriptReference Path="~/scripts/scripts.js" />
            </Scripts>
    </asp:ScriptManager>
    <br />
    <table class="ui-accordion">
        <tr>
            <td>
                <asp:TextBox ID="txt" runat="server" TextMode="MultiLine" 
                    style="WIDTH: 690px; HEIGHT: 260px; margin-right: 44px;" rows="16" Columns="79"></asp:TextBox>
                <br />
                <asp:TextBox ID="txtMsg" runat="server" Width="400"></asp:TextBox><input id="btn" type="button" value="Send" onclick="button_clicked()" class="btn" />
            </td>
            <td>
                <asp:Label ID="Label1" runat="server" Text="Room Members: "></asp:Label>
                <br />
                <asp:ListBox ID="lstMembers" runat="server" Width="100" Enabled="false" Height="249px"></asp:ListBox>
            </td>
        </tr>
    </table>
    </div>
    </div>
</asp:Content>



Chat.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script;
using System.Collections;
using System.Collections.Generic;
using GameBL;
using GameDB;

namespace GameWebsite
{
    public partial class Chat : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
                Response.Redirect("Default.aspx");
            if (string.IsNullOrEmpty(Request.QueryString["rid"]))
                Response.Redirect("Default.aspx");

            txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
            if (!IsPostBack)
            {
                hdnRoomID.Value = Request.QueryString["rid"];
                ChatRoom room = ChatEngine.GetRoom(hdnRoomID.Value);
                string prevMsgs = room.JoinRoom(Session["UserName"].ToString(), Session["UserName"].ToString());
                txt.Text = prevMsgs;
                foreach (string s in room.GetRoomUsersNames())
                {
                    lstMembers.Items.Add(new ListItem(s, s));
                }
            } 
        }

        #region Script Callback functions

        /// <summary>
        /// This function is called from the client script 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="roomID"></param>
        /// <returns></returns>
        [WebMethod]
        static public string SendMessage(string msg, string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                string res = "";
                if (room != null)
                {
                    res = room.SendMessage(msg, HttpContext.Current.Session["UserName"].ToString());
                }
                return res;
            }
            catch (Exception ex)
            {

            }
            return "";
        }


        /// <summary>
        /// This function is called peridically called from the user to update the messages
        /// </summary>
        /// <param name="otherUserID"></param>
        /// <returns></returns>
        [WebMethod]
        static public string UpdateUser(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    string res = "";
                    if (room != null)
                    {
                        res = room.UpdateUser(HttpContext.Current.Session["UserName"].ToString());
                    }
                    return res;
                }
            }
            catch (Exception ex)
            {

            }
            return "";
        }


        /// <summary>
        /// This function is called from the client when the user is about to leave the room
        /// </summary>
        /// <param name="otherUser"></param>
        /// <returns></returns>
        [WebMethod]
        static public string LeaveRoom(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                    room.LeaveRoom(HttpContext.Current.Session["UserName"].ToString());
            }
            catch (Exception ex)
            {

            }
            return "";
        }


        /// <summary>
        /// Returns a comma separated string containing the names of the users currently online
        /// </summary>
        /// <param name="roomID"></param>
        /// <returns></returns>
        [WebMethod]
        static public string UpdateRoomMembers(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    IEnumerable<string> users = room.GetRoomUsersNames();
                    string res = "";

                    foreach (string s in users)
                    {
                        res += s + ",";
                    }
                    return res;
                }
            }
            catch (Exception ex)
            {
            }
            return "";
        }
        #endregion
    }
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1