Thursday, August 11, 2011

Simple Chat Prototype using ASP.Net MVC

This chat application is a browser based chat.It uses ajax calls to get and send data.
On the server i have used two singletons which handle the messages and the list of online users

Controller and Models

//User Collection
namespace ChatClient.Models
{
    public sealed class UserCollection
    {

        private static UserCollection instance = null;
        private List users = new List();
        private static readonly object padlock = new object();

         UserCollection()
         {
         }

         public static UserCollection Instance
         {
                get
                {
                    lock (padlock)
                    {
                        if (instance == null)
                        {
                            instance = new UserCollection();
                        }
                        return instance;
                    }
                }
          }

         public void AddToUserCollection(User user)
         {
             users.Add(user);
         }

         public void RemoveFromUserCollection(User user)
         {
             users.Remove(user);
         }

         public bool IsUserPresent(User user)
         {
             return users.Exists(p => p.Name == user.Name);
         }
         
    }
}

public class User
    {
        public string Name { get; set; }
        public bool Online { get; set; }

    }

public class ChatMessage
    {
        public string Message { get; set; }
        public string MessageDateTime { get; set; }
        public User FromUser { get; set; }
        public User ToUser { get; set; }
    }

  public class MessageCollection
    {

         private static MessageCollection instance = null;
         private List chatMessages = new List();
        private static readonly object padlock = new object();

        MessageCollection()
         {
         }

        public static MessageCollection Instance
         {
                get
                {
                    lock (padlock)
                    {
                        if (instance == null)
                        {
                            instance = new MessageCollection();
                        }
                        return instance;
                    }
                }
          }

        public void AddToMessageCollection(ChatMessage chatMessage)
         {
             chatMessages.Add(chatMessage);
         }

        public void RemoveFromMessageCollection(User user)
         {
             chatMessages.RemoveAll(p => p.ToUser.Name == user.Name);
         }

         public List GetMessages(User user)
         {
             return chatMessages.Where(p => p.ToUser.Name == user.Name).Select(p => p).ToList();
         }

    }


//Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChatClient.Models;
using System.Runtime.Remoting.Messaging;

namespace ChatClient.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        UserCollection collection = UserCollection.Instance;
        MessageCollection messageCollection = MessageCollection.Instance;

        public ActionResult Index()
        {
            return View();
        }

        public string Register(string userName)
        {
            if (!collection.IsUserPresent(new User() { Name = userName, Online = true }))
            {
                collection.AddToUserCollection(new User()
                {
                    Name = userName,
                    Online = true,
                });
            }
            return "Online";
        }

        public JsonResult SendMessage(string message, string toUser, string fromUser)
        {
            ChatMessage chatMessage = new ChatMessage()
            {
                FromUser = new User() {
                            Name = fromUser,
                            Online = true
                },
                ToUser = new User()
                {
                    Name = toUser,
                    Online = true
                },
                Message = message,
                MessageDateTime = DateTime.Now.ToString()
            };
            messageCollection.AddToMessageCollection(chatMessage);
            return Json(chatMessage);
        }

        public JsonResult GetMessages(string userName)
        {
            if (messageCollection.GetMessages(new User() { Name = userName, Online = true }).Count > 0)
            {
                List messages = messageCollection.GetMessages(new User() { Name = userName, Online = true }).Select(p => p).ToList();
                Action remove = delegate()
                {
                    RemoveMessages(userName);
                };
                IAsyncResult result = remove.BeginInvoke(RemoveMessagesEnd, null);
                return Json(messages.ToArray(),JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        public void RemoveMessagesEnd(IAsyncResult result)
        {
            object state = (AsyncResult)result.AsyncState;
        }

        public void RemoveMessages(string userName)
        {
            messageCollection.RemoveFromMessageCollection(new User() { Name = userName, Online = true });
        }
        public ActionResult About()
        {
            return View();
        }
    }
}




View


  
  
<%= Html.Label("UserName") %> <%= Html.TextBox("userName")%> <%= Html.Label("ToUser") %> <%=Html.TextBox("toUser") %>
<%= Html.Label("ChatHistory") %> <%= Html.TextArea("ChatHistory")%> <%= Html.Label("ChatBox") %> <%= Html.TextBox("ChatBox") %>