You must Sign In to post a response.
  • Category: ASP.NET

    One to one chat application in asp.net

    hi Ankur..
    i read ur post and i got some idea , but when i'm click on the online user and send them a message i didn't get the username in message box while sending the message. i' always getting undefine user name.
  • #743046
    Hi,
    Can you please post complete details abut the issue? What exactly you are doing and also the portion code you are getting error.


    Regards,
    Asheej T K

  • #743050
    thank you sir for ur response
    I refer this link
    http://anantgarg.com/2009/05/13/gmail-facebook-style-jquery-chat/

    in code behind of Chat.aspx code is and i'm storing username in session vaiable Name.


    public partial class _Default : System.Web.UI.Page
    {
    protected SqlConnection con;
    protected SqlCommand cmd;
    string constr = "server=PANKAJ-PC\\SQLEXPRESS;uid=sa;pwd=123456;database=SocialNetDB";

    protected void Page_Load(object sender, EventArgs e)
    {
    getUserStatus();
    // Session["username"] = Session["Name"].ToString();

    if (Session["chatHistory"] == null)
    Session["chatHistory"] = new Hashtable();

    if (Session["openChatBoxes"] == null)
    Session["openChatBoxes"] = new Hashtable();

    string action = Request.QueryString["action"];

    switch (action)
    {
    case "chatheartbeat":
    chatheartbeat();
    break;
    case "sendchat":
    sendchat();
    break;
    case "closechat":
    closechat();
    break;
    case "startchatsession":
    startchatsession();
    break;

    }
    }


    protected void getUserStatus()
    {
    DataTable dt = new DataTable();
    string query = "select * from Register where Id In (select MyId from [Friends] where FriendId='" + Session["currentProfileId"] + "' And Status=1 UNION select FriendId from [Friends] where MyId='" + Session["currentProfileId"] + "' and Status=1)";
    dt = DataBaseClass.GetData(query);
    if (dt.Rows.Count > 0)
    {
    Repeater1.Visible = true;
    Repeater1.DataSource = dt;

    Repeater1.DataBind();

    //DataList1.Visible = true;
    //DataList1.DataSource = dt;
    //DataList1.DataBind();
    }
    else
    {

    }

    }
    protected void ImgBtnClk_Click(object sender, ImageClickEventArgs e)
    {
    Session["currentProfileId"] = (((ImageButton)sender).CommandArgument.ToString());

    }

    private void startchatsession()
    {
    string items = string.Empty;
    //Hashtable openChatBoxes = (Hashtable)Session["openChatBoxes"];
    //Hashtable chatHistory = (Hashtable)Session["chatHistory"];

    if (((Hashtable)Session["openChatBoxes"]) != null && ((Hashtable)Session["openChatBoxes"]).Keys.Count > 0)
    {
    foreach (String key in ((Hashtable)Session["openChatBoxes"]).Keys)
    items += chatBoxSession(key);
    }

    if (items != "" && items.EndsWith(","))
    {
    items = items.Remove(items.Length - 1);
    }

    string dq = @"""";
    StringBuilder jsonItems = new StringBuilder();
    jsonItems.Append("{");
    jsonItems.Append(dq + "Name" + dq + ":" + dq + Session["Name"].ToString() + dq + ",");
    jsonItems.Append(dq + "items" + dq + ":" + "[" + items + "]");
    jsonItems.Append("}");

    HttpContext.Current.Response.ContentType = "application/json";
    HttpContext.Current.Response.Write(jsonItems.ToString());
    }

    private void closechat()
    {
    string chatBox = Request.Form["chatbox"] as string;
    ((Hashtable)Session["openChatBoxes"])[chatBox] = null;
    Response.Write("1");
    }

    private void sendchat()
    {
    //Hashtable chatHistory = (Hashtable)Session["chatHistory"];
    //Hashtable openChatBoxes = (Hashtable)Session["openChatBoxes"];
    string from = Session["Name"].ToString();
    string to = Request.Form["to"].ToString();
    string message = Request.Form["message"].ToString();

    string messagesan = sanitize(message);

    if (((Hashtable)Session["chatHistory"])[to] == null)
    ((Hashtable)Session["chatHistory"])[to] = "";

    ((Hashtable)Session["chatHistory"])[to] += "{\"s\" : \"1\", \"f\" : \"" + to + "\", \"m\" : \"" + messagesan + "\"},";

    string sql = "insert into chat ([from],[to],message,sent) values ('" + from + "', '" + to + "','" + message + "',GetDate())";
    SqlConnection connection = new SqlConnection(constr);
    connection.Open();
    SqlCommand command = connection.CreateCommand();
    command.CommandType = CommandType.Text;
    command.CommandText = sql;
    try
    {
    int result = command.ExecuteNonQuery();
    }
    catch (Exception ed)
    {
    Response.Write(ed.Message);
    }

    Response.Write("1");
    }

    private string chatBoxSession(string chatBox)
    {
    string items = string.Empty;

    if (((Hashtable)Session["chatHistory"])[chatBox] != null)
    {
    items = ((Hashtable)Session["chatHistory"])[chatBox] as string;
    }

    return items;
    }

    private string sanitize(string text)
    {
    text = text.Replace("\n\r", "\n");
    text = text.Replace("\r\n", "\n");
    text = text.Replace("\n", "<br>");
    return text;
    }


    private void chatheartbeat()
    {
    //Hashtable chatHistory = (Hashtable)Session["chatHistory"];
    //Hashtable openChatBoxes = (Hashtable)Session["openChatBoxes"];

    string sql = "select * from chat where [to] = '" + Session["Name"].ToString() + "' AND recd = 0 order by MId ASC";
    //TODO :: Connect to database and get the data.
    SqlConnection connection = new SqlConnection(constr);
    connection.Open();
    SqlCommand command = connection.CreateCommand();
    command.CommandText = sql;
    command.CommandType = CommandType.Text;
    SqlDataReader reader = null;
    try
    {
    reader = command.ExecuteReader();
    }
    catch (Exception ed)
    {
    Response.Write(ed.Message);
    }
    string items = string.Empty;

    Hashtable chatBoxes = new Hashtable();

    //Loop through all the records fetched using above query.
    while (reader.Read())
    {
    string from = reader["from"].ToString(); // Get the from value from the DataRow
    string message = reader["message"].ToString(); // Get the message value from the DataRow
    string sent = reader["sent"].ToString(); // Get the sent value from the DataRow

    //if (((Hashtable)Session["openChatBoxes"])[from] == null && ((Hashtable)Session["chatHistory"])[from] != null)
    // items = ((Hashtable)Session["chatHistory"])[from] as string;

    items += "{\"s\" : \"0\", \"f\" : \"" + from + "\", \"m\" : \"" + message + "\"},";

    if (((Hashtable)Session["chatHistory"])[from] == null)
    ((Hashtable)Session["chatHistory"])[from] = string.Empty;

    ((Hashtable)Session["chatHistory"])[from] += "{\"s\" : \"0\", \"f\" : \"" + from + "\", \"m\" : \"" + message + "\"},";
    ((Hashtable)Session["openChatBoxes"])[from] = sent;
    }

    //Session["openChatBoxes"] = openChatBoxes;
    //Session["chatHistory"] = chatHistory;

    reader.Close();
    reader = null;


    //TODO :: UPdate the database.
    sql = "update chat set recd = 1 where [to] = '" + Session["Name"].ToString() + "' and recd = 0";
    command.CommandText = sql;
    command.CommandType = CommandType.Text;
    try
    {
    command.ExecuteNonQuery();
    }
    catch (Exception ed)
    {
    Response.Write(ed.Message);
    }

    if (items != "" && items.EndsWith(","))
    {
    items = items.Remove(items.Length - 1);
    }


    StringBuilder jsonItems = new StringBuilder();
    jsonItems.Append("{");
    jsonItems.Append("\"items\": [" + items + "]");
    jsonItems.Append("}");

    connection.Close();
    command = null;

    HttpContext.Current.Response.ContentType = "application/json";
    HttpContext.Current.Response.Write(jsonItems.ToString());
    }


    Below Is The Jquery File

    chat.js

    Delete Attachment

  • #743051
    this is the chatbox screenshoots

    Delete Attachment

  • #743053
    You must store all the user name in the session variable or a temporary variable for the application where you can access the message,

    As soon as you transfer the message to other user then pass the user name as well.

    Where is the issue in your code for user name please debug.

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM

  • #743144
    Hi,

    SignalR is a latest technology with .Net which can help creating real time applications

    You can read this article for SignalR details.
    http://www.dotnetspider.com/resources/45591-What-is-SignalR.aspx

    For creating a chat application following is the site that gives sample code.

    http://www.bluelemoncode.com/post/2013/02/17/One-to-one-chat-using-Aspnet-SignalR-groups.aspx

  • #763153
    Hi pankajK,

    Could you please post full code of chat.aspx and chat.aspx.cs and sqltable

    it would helpfull to us

    Thanks,
    Mrali.


  • Sign In to post your comments