Asp.net web Chat application

Chat web application in asp.net programming :



Chat application is very popular for any web site .as we see in social service web site the chat application is all wage  present where .so the crease of chat application is more than other application .now here we discuss how to create a chat application or chatting web site .i think it help you .
It is very easy by .net ,there are some steps.
For creating a chat application on asp.net there are fallowing thing you need .As fallows:-

1. Create a web site in asp.net.
2. Create a handler (that is use to handle chat flow and data flow).
3.  Create a chat room in xml if u does not want to connect database.
4.  Create  .aspx from for design chat look (user end form where user play chatting ).
5 create .aspx.cs for coding sport to .aspx from. (Code in asp.net).

Know here we create code one by one ………………………….

1.     Create Handler(XHandle.cs) in App_code folder because it is a class file .and you know that  all class files assemble into App_Code folder in asp.net Programming.

Code of Xhandle.cs (C# code Asp.net web Chat application):

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public class XHandle
{
    private string _path;
    private string _xPageName;
    private string _FullPath;

    private XDocument _xDoc;
    private bool _xDocCreated;

    private XElement _usersRoot;
    private int _onlineUsers;


          public XHandle(string _path)
          {
        this._path = _path;
        this._xDocCreated = false;
        this._xPageName = "Default";
        this._FullPath = this._path + @"\" + this._xPageName + ".xml";
        this._onlineUsers = 0;

        //Check the xml page if already exist
        LoadXPage();

        //or create it if it doesnt
        if (!_xDocCreated)
        {
            CreateXPage();
        }
       
          }

    public XHandle(string _path, string ChatRoomName)
    {
        this._path = _path;
        this._xDocCreated = false;
        this._xPageName = ChatRoomName;
        this._FullPath = this._path + @"\" + this._xPageName + ".xml";

        //Check the xml page if already exist
        LoadXPage();

        //or create it if it doesnt
        if (!_xDocCreated)
        {
            CreateXPage();
        }

    }

    private void CreateXPage()
    {
        _xDoc = new XDocument();
        XDeclaration dec = new XDeclaration("1.0", "utf-8", "yes");
        _xDoc.Declaration = dec;
        _usersRoot = new XElement("users");
        _xDoc.Add(_usersRoot);
        _xDoc.Save(_FullPath);
        _xDocCreated = true;
    }

    private void LoadXPage()
    {
        try
        {
            _usersRoot = XElement.Load(_FullPath);
            _xDocCreated = true;
        }
        catch
        {
            _xDocCreated = false;
        }
    }

    public void Say(string userName, string msg, DateTime dateTime)
    {
        XElement user = new XElement("user");
        XElement elementName = new XElement("name", userName);
        XElement elementLastMsg = new XElement("message", msg);
        XElement elementDate = new XElement("date", dateTime.ToString());
        user.Add(elementName);
        user.Add(elementLastMsg);
        user.Add(elementDate);
        _usersRoot.Add(user);
        _usersRoot.Save(_FullPath);
    }

    public void Join(string userName, DateTime dateTime)
    {
        string systemMsg = userName + " joined chat room.";
        this.Say(userName, systemMsg, dateTime);
    }

    public void Leave(string userName, DateTime dateTime)
    {
        var user = from o in _usersRoot.Elements("user")
                   where (string)o.Element("name").Value == userName
                   select o;

        user.Remove();

        _usersRoot.Save(_FullPath);
    }

    public List<string> GetOnlineNames()
    {
        List<string> names = new List<string>();
        var users = (from o in _usersRoot.Elements("user")
                    select o).Distinct();

        foreach (var user in users)
        {
            if (!names.Contains(user.Element("name").Value))
            {
                names.Add(user.Element("name").Value);
            }
        }
        _onlineUsers = names.Count;

        return names;
    }

    public int GetNumberOfOnlines()
    {
        var users = (from o in _usersRoot.Elements("user")
                     select o).Distinct();
        List<string> names = new List<string>();
        foreach (var user in users)
        {
            if (!names.Contains(user.Element("name").Value))
            {
                names.Add(user.Element("name").Value);
            }
        }
        if (names.Count > 0)
        {
            _onlineUsers = names.Count;
            return names.Count;
        }
        _onlineUsers = 0;
        return 0;
    }

    public List<string> GetMessagesHistory()
    {
        List<string> messages = new List<string>();
        var users = (from o in _usersRoot.Elements("user")
                     where o.Element("message").Value != string.Empty
                     orderby DateTime.Parse(o.Element("date").Value) ascending
                     select o).Distinct();
        foreach (var user in users)
        {
            string fullString = user.Element("name").Value + " : " + user.Element("message").Value;
            if (!messages.Contains(fullString))
            {
                messages.Add(fullString);
            }
        }
        return messages;
    }

   
}

2.Create Chat room in xml if you does not use data base:


ChatRoom.xml
<?xml version="1.0" encoding="utf-8"?>
<users />

3. Now create .aspx from for design (user end code )

Code of .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChatRoom.aspx.cs" Inherits="ChatRoom" %>

<%@ Register assembly="Anthem" namespace="Anthem" tagprefix="anthem" %>





<!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>Untitled Page</title>
    <style type="text/css">

        .style1
        {
            width: 62%;
        }
        .style2
        {
            width: 102px;
        }
        .style3
        {
            width: 333px;
        }
        .style4
        {
            width: 102px;
            height: 357px;
        }
        .style5
        {
            width: 333px;
            height: 357px;
        }
        .style6
        {
            height: 357px;
            width: 280px;
        }
        #Text1
        {
            height: 36px;
            width: 183px;
        }
        .style7
        {
            width: 280px;
        }
    </style>
</head>
<body onunload="Leave(); return false;">
<script type="text/javascript">
function Leave()
{
    Anthem_InvokePageMethod('Leave', null, null);
}

</script>
    <form id="form1" runat="server" defaultbutton="ButtonSend">
    <div>
   
<table class="style1">
    <tr>
        <td class="style2">
            <anthem:Label ID="LabelUserName" runat="server">
            &nbsp;
            </anthem:Label>
            <anthem:Label ID="Label1" runat="server">
                &nbsp;User Name:</anthem:Label>
        </td>
        <td class="style3">
<anthem:TextBox ID="TextBoxName" runat="server" Height="37px" Width="381px"></anthem:TextBox>&nbsp;
            </td>
        <td class="style7">
            <anthem:Button ID="ButtonJoin" runat="server" Height="42px"
                onclick="ButtonJoin_Click" Text="Join" Width="91px" />
        </td>
    </tr>
    <tr>
        <td class="style2">
           </td>
        <td class="style3">
            <anthem:Label ID="LabelError" runat="server" AutoUpdateAfterCallBack="True"
                UpdateAfterCallBack="True"></anthem:Label>
            </td>
        <td class="style7">
           </td>
    </tr>
    <tr>
        <td class="style4">
            &nbsp;</td>
        <td class="style5">
            <anthem:ListBox ID="ListBox2" runat="server" Height="352px" Width="385px"
                AutoUpdateAfterCallBack="True">
            </anthem:ListBox>
        </td>
        <td class="style6">
            <anthem:Timer ID="Timer1" runat="server">
            </anthem:Timer>
            <anthem:ListBox ID="ListBox1" runat="server" Height="352px" Width="191px"
                AutoUpdateAfterCallBack="True" TextDuringCallBack="Loading...">
            </anthem:ListBox>
            </td>
    </tr>
    <tr>
        <td class="style2">
           </td>
        <td class="style3">
            <anthem:TextBox ID="TextBoxType2" runat="server" Height="37px" Width="390px"></anthem:TextBox>
            </td>
        <td class="style7">
            <anthem:Button ID="ButtonSend" runat="server" Height="41px"
                onclick="ButtonSend_Click" Text="Send" Width="90px" />
            </td>
    </tr>
</table>


    </div>
    </form>
</body>
</html>

4. Create back end code of .aspx file (.aspx.cs)


Code of .aspx.cs file
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class ChatRoom : System.Web.UI.Page
{
    XHandle xmll;
   
    List<string> names;
    List<string> msgs;

    private delegate void AsyncCallingNames();
    private delegate void AsyncCallingMessages();

    AsyncCallingNames callerNames;
    AsyncCallingMessages callerMessages;

    protected void Page_Load(object sender, EventArgs e)
    {
        Anthem.Manager.Register(this);

        xmll = new XHandle(Server.MapPath("App_Data"), "FirstChatRoom");
        //Get chat room name from user or chat admin

        int x = xmll.GetNumberOfOnlines();
        if (Session["userName"] != null)
        {
            LabelError.Text = "Online, Users Online: " + x.ToString();
        }
        else
        {
            LabelError.Text = "Offline, Users Online: " + x.ToString();
        }

        Timer1.Interval = 2;
        //I set it to 1 second, and it wroked very well

        Timer1.Tick += new EventHandler(Timer1_Tick);

        callerNames = new AsyncCallingNames(this.RefreshListNames);
        callerMessages = new AsyncCallingMessages(this.RefreshMessages);
    }


    void Timer1_Tick(object sender, EventArgs e)
    {
        if (Session["userName"] != null)
        {
            IAsyncResult resultN = callerNames.BeginInvoke(null, null);
            if (!resultN.IsCompleted)
            {
                callerNames.EndInvoke(resultN);
            }

            IAsyncResult resultM = callerMessages.BeginInvoke(null, null);
            if (!resultM.IsCompleted)
            {
                callerMessages.EndInvoke(resultM);
            }
            TextBoxType2.Focus();
        }
        else
        {
            Timer1.StopTimer();
            TextBoxType2.Text = "You have to join with a name first..";
        }
    }


    private void RefreshListNames()
    {
        ListBox1.Items.Clear();
        names = xmll.GetOnlineNames();
        foreach (var name in names)
        {
            ListBox1.Items.Add(name);
        }
    }

    private void RefreshMessages()
    {
        ListBox2.Items.Clear();
        msgs = xmll.GetMessagesHistory();
        foreach (var msg in msgs)
        {
            ListBox2.Items.Add(msg);
        }
    }

    protected void ButtonJoin_Click(object sender, EventArgs e)
    {
        if (Session["userName"] == null)
        {
            Session["userName"] = TextBoxName.Text.ToString();
            xmll.Join(Session["userName"].ToString(), DateTime.Now);

            TextBoxName.Enabled = false;

            Timer1.StartTimer();

            TextBoxType2.Focus();
        }
    }
    protected void ButtonSend_Click(object sender, EventArgs e)
    {
        if (Session["userName"] != null)
        {
            string name = (string)Session["userName"];
            string msg = TextBoxType2.Text.ToString();
            xmll.Say(name, msg, DateTime.Now);
            TextBoxType2.Text = "";
            TextBoxType2.Focus();
        }
        else
        {
            LabelError.Text = "You have to join with a name first..";
        }
    }

    [Anthem.Method]
    public void Leave()
    {
        Timer1.StopTimer();

        if (Session["userName"] != null)
        {
            string name = (string)Session["userName"];
            xmll.Leave(name, DateTime.Now);

            LabelError.Text = "Offline";
        }
    }
}



For this application you need some assemblies file, you download these file form Internet we give name here and link .
a.    Anthem.dll
Download link..
b.    Anthem.pdb
Download link..
c.    AnthemExtensions.dll
d.   AnthemExtensions.pdb
e.    Anthem.pdb
 http://www.rcsb.org/pdb/static.do?p=download/ftp/index.html

Download Project here..


Asp.net Related Other Post:


Popular posts from this blog