Chating in Asp.net using Ajax (pop-up windows)

Source: Internet
Author: User
    • Download aspchat-2.29 MB
Introduction

In this post I want to share my work on developing chatting application that can be used in your regular ASP. NET applications. I am using Ajax and SQL Server for backend. this can be used in ASP. NET 2.0 or more, as I am using the updatepanel.

Using the code

The application works as follows-

    • List of online users are displayed.

      • Online users list can be loaded from the backend database, logging an entry when a user logs into the application, the user names will be displayed as hyperlinks with a unique chat id for each.
  • The current logged-in user will click on a selected to user name to open a new chat window, and types a message .

      • On click of the username openchatbox () function is called with the chatid as parameter. when the user types any message and clicks on send button, the message is sent to server and stored to the database with chat ID supplied.
    Collapse Copy code
    Function openchatbox (UID, chatid) {var win = Window. Open ( "  Chatbox. aspx? Uid =" + Uid + "  & Cid =" + Chatid, "  Chatwindow" + Chatid + document. getelementbyid ( ' Hidcurrentuser' ). Value , "  Status = 0, toolbar = 0, menubar = 0, width = 450, Height = 550" ); Top = Top + 50 ; If (Top > Screen. availheight- 550 ) Top = 100 ; Left = left + 50 ; If (Left > Screen. availwidth- 450 ) Left = 100 ; Win. moveTo (left, top); chats [chats. Length] = win; Return   False ;}

    The storing of message is implemented in ASP. NET.

    Collapse Copy code
      Private   Sub Sendmessage ( Byval MSG As   String ) Dim Con As Sqlconnection =New Sqlconnection (_ "  Data Source =. \ sqlexpress; attachdbfilename = D: \ Dev \ projects \ webchat \ app_data \ webchat. MDF; Integrated Security = true; user instance = true" ) Con. open () Dim Comm As Sqlcommand = New Sqlcommand ( "  Stp_sendmessage" , Con) Comm. commandtype = commandtype. storedprocedure Dim Paramsender As Sqlparameter =New Sqlparameter (_ "  @ Sender" , Sqldbtype. varchar, 10 ) Paramsender. value = httpcontext. Current. User. Identity. Name comm. Parameters. Add (paramsender) Dim Paramrec As Sqlparameter = New Sqlparameter (_ "  @ Reciever" , Sqldbtype. varchar, 10 ) Paramrec. value = viewstate ( "  UID" ) Comm. Parameters. Add (paramrec) Dim Parammsg As Sqlparameter = New Sqlparameter (_ "  @ MSG" , Sqldbtype. varchar, 1000 ) Parammsg. value = MSG comm. Parameters. Add (parammsg) '  Store the chat ID supplied from Browser          Dim Paramchatid As Sqlparameter = New Sqlparameter (_"  @ Chatid" , Sqldbtype. varchar, 100 ) Paramchatid. value = viewstate ( "  Vwchatid" ). Tostring () Comm. Parameters. Add (paramchatid) Comm. executenonquery () con. Close () End   Sub 
  • On the recipient's screen a new pop-up window will appear.

      • One every users home page a script is run for every 5 seconds to ping the server for any messages.
    Collapse Copy code
    Function pingserver () {pingserverformsg () setTimeout (pingserver,5000);} Function pingserverformsg (){//Use ajax to call the getchatmsg. aspx to get any new messages.XMLHTTP = getxmlhttpobject (statechangehandler );}

    This JavaScript message will call the getchatmsg. ASPX page for the new messages, and below is the code for getchatmsg. aspx

    Collapse Copy code
     Imports System. Data Imports System. Data. sqlclient Partial   Public   Class Getchatmsg Inherits System. Web. UI. Page Protected   Sub Page_load ( Byval Sender As Object, Byval E As System. eventargs) Handles   Me . Load response. Clear () response. clearcontent () '  Set response to not to cache, to avoid the Ajax from displaying old message. Response. addheader ("  Cache-control" , "  No-cache, must-revalidate" ) Dim DS As Dataset = getmessage (httpcontext. Current. User. Identity. Name) Dim Strmsg As   String = "  "          If DS. Tables. Count> 0   Then             If DS. Tables ( 0 ). Rows. Count> 0   Then                  For   Each Dr As Datarow In DS. Tables ( 0 ). Rows If Strmsg. length> 0   Then Strmsg + = "  #"                      End  If Strmsg + = DR ( "  Sender" ). Tostring () + "  &" Strmsg + = DR ( "  Chatid" ). Tostring () + "  &" Strmsg + = DR ( "  MSG" ). Tostring (). Replace ( "  &" , " _ @ Amp __" ). Replace ( "  #" , "  _ @ Hash __" ) Next              End   If          End   If Response. Write (strmsg) response. End () End   Sub      Private   Function Getmessage (Byval Struid As   String ) As Dataset Dim Dsmsgs As Dataset = New Dataset () Dim Con As Sqlconnection = New Sqlconnection (_ "  Data Source =. \ sqlexpress; attachdbfilename = D: \ Dev \ projects \ webchat \ app_data \ webchat. MDF; Integrated Security = true; user instance = true" ) Con. open () Dim Comm As Sqlcommand = New Sqlcommand ( "  Stp_getmessage" , Con) Comm. commandtype = commandtype. storedprocedure Dim Paramsender As Sqlparameter = New Sqlparameter (_ "  @ Uid" , Sqldbtype. varchar, 10 ) Paramsender. value = httpcontext. Current. User. Identity. Name comm. Parameters. Add (paramsender) If (Request. querystring ( "  CID" ) <> Nothing ) Then              Dim Paramchatid As Sqlparameter = New Sqlparameter (_ "  @ Chatid" , Sqldbtype. varchar, 100 ) Paramchatid. value = request. querystring ("  CID" ) Comm. Parameters. Add (paramchatid) End   If          Dim Da As Sqldataadapter = New Sqldataadapter (Comm) Da. Fill (dsmsgs) con. Close () Return Dsmsgs End   Function  End   Class 

    On the Browser Side on getting new message, the browser will open the pop-up if the chatid is new, or will show the message if the pop-up is already open for the chatid associated with the new message.

    Collapse Copy code
    Function statechangehandler (){ //  Readystate of 4 or 'complete' represents that data has been returned      If (XMLHTTP. readystate = 4 | XMLHTTP. readystate = '  Complete' ){ // Gather the results from the callback VaR STR = XMLHTTP. responsetext; If (STR! = "  " ){ //  Document. getelementbyid ('txtmsg'). value = STR;              //  Eval (STR ); VaR msgs = Str. Split ( '  #' ); For (IND = 0 ; Ind < Msgs. length; ind ++) {msgs [ind] = msgs [ind]. Replace ( "  _ @ Hash __" , "  #" ); Var MSG = msgs [ind]. Split ( "  &" ); MSG [ 0 ] = MSG [ 0 ]. Replace ( "  _ @ Amp __" , "  &" ); MSG [ 1 ] = MSG [1 ]. Replace ( "  _ @ Amp __" , "  &" ); MSG [ 2 ] = MSG [ 2 ]. Replace ( "  _ @ Amp __" , "  &" ); Var blnexisting = False ; For (Iind = 0 ; Iind< Chats. length; iind ++ ){ Try { If (Chats [iind]! = NULL & chats [iind]. Name = "  Chatwindow" + MSG [ 1 ] + Document. getelementbyid ( '  Hidcurrentuser' ). Value ) Blnexisting = True ;} Catch (E ){}} If (Blnexisting = False ) Openchatbox (MSG [ 0 ], MSG [ 1 ]) ;}}}
  • the users can communicate through the current window.
    • the recipient can type in the message to reply back using the same window. the pop-up window has the screen chatbox. aspx, which has the chatbox. JS reference of JavaScript code to ping the server again for every 1 sec. but this time it uses the chat ID assigned to the that window. and thus every chat has a unique chat ID, and chat messages are maintained at the backend by the chatid and pop-up windows communicate through the chat id. an update panel is used here to avoid the flickering of the chat window when user clicks send message. and when the message is recieved by the recipient the message is deleted by the server.
    • A single user can communicate with multiple users at a time.

      • The user can chat with any number of users as the pop-up windows are used for each chat with the unique chat ID for the chat. the chat id is generated as 'timestamp + senderid + recipient id '.

On click of the send button the typed message will be saved by the code behind to a table in SQL Server (here any other database can be used ). on recipient side on Ajax call the message reader will read the messages related to the recipient and send to recipient. please check the attached source code for ASP. net code which is for Visual Studio 2008, but same code can be used for VS 2005 (Asp. NET 2.0) with out changes.

When the first user sends a message, the message is saved to backend for the selected user. when the application running on the recipient (implemented in default. aspx in sample) uses the Ajax to ping the server for messages for each 5 seconds.


Enhancements

    • Developers can try to implement saving Chat History.
    • The list of online users can be implemented in a user control to make it reusable.
    • Chat window can be changed to include time of message and to include images.


Reprinted: http://www.codeproject.com/KB/aspnet/Chating_in_asp_net_Ajax.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.