Click here to Skip to main content
15,925,202 members
Articles / Web Development / ASP.NET
Article

Simple chat application for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.70/5 (84 votes)
26 May 20041 min read 534.5K   30.9K   175   86
Very easy Web application of a chat room for Internet Explorer 5+ in ASP.NET.

Sample Image - SimpleChat.jpg

Introduction

And why not, how to create an easy chat room for your web site? Well, the best way is to use a nice database to store messages; however, for demo purposes, I'll use a static array. I know, you won't be able to use it in your web farm. Take this article as the concept, not as a solution. This simple web chat program is intended to work in any browser supporting <iFrame>.

Also, you can select multiple chat rooms. Why not extend from there and more from channel to channel.

Background

Some months ago, I was looking for a complete on-line customer service ASP.NET control to make my life easier, did not find anything interesting, so I built my own.

Using the code

Replace this class if you are using a database to save the messages:

C#
public class Chat
{
        static protected ArrayList pArray = new ArrayList();
        

        static public void AddMessage(string sDealer, 
                              string sUser, string sMsg)
        {
            string sAddText = sDealer + "~" + sUser + "~" + sMsg;
            pArray.Add(sAddText);

            if ( pArray.Count > 200 )
            {
                pArray.RemoveRange(0,10);
            }
        }

        static public string GetAllMessages(string sDealer)
        {
            string sResponse = "";

            for (int i=0; i< pArray.Count; i++)
            {
                sResponse = sResponse + 
                    FormatChat(pArray[i].ToString(), sDealer);
            }

            return(sResponse);
        }

        static private string FormatChat(string sLine, string sDealer)
        {
            int iFirst = sLine.IndexOf("~");
            int iLast = sLine.LastIndexOf("~");

            string sDeal = sLine.Substring(0, iFirst);
            if ( sDeal != sDealer)
                return("");

            string sUser = sLine.Substring(iFirst+1, iLast-(iFirst+1));
            
            string sMsg = sLine.Substring(iLast+1);

            string sRet = "" + sUser + ": " + sMsg + "";

            return(sRet);
        }
    }

The above code reads and writes from the static array like in a database. The code only allows having 200 messages in the array, after that it deletes the top 10 at the time.

The Chat page is pretty simple; this is the code behind aspx.cs:

C#
public class ChatWin : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.TextBox TB_ToSend;
        protected System.Web.UI.WebControls.Button BT_Send;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            if ( Page.IsPostBack == false )
            {
                if ( Request.Params["Channel"] != null )
                    Session["ChatChannel"] = 
                       Request.Params["Channel"].ToString();
                else
                    Session["ChatChannel"] = "1";
                
            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <SUMMARY>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </SUMMARY>
        private void InitializeComponent()
        {    
            this.BT_Send.Click += 
               new System.EventHandler(this.BT_Send_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        public string GetChatPage()
        {
            return("TheChatScreenWin.aspx");
        }

        private void BT_Send_Click(object sender, System.EventArgs e)
        {
            string sChannel = "";
            string sUser = "";

            if ( Request.Params["Channel"] != null )
                sChannel = Request.Params["Channel"].ToString();
            else
                sChannel = "1";

            if ( Request.Params["User"] != null )
                sUser = Request.Params["User"].ToString();
            else
            {
                Random pRan = new Random();
                int iNum = pRan.Next(9);
                sUser = "Annonymouse" + iNum;
            }

            
            if ( TB_ToSend.Text.Length > 0)
            {
                PageModule.Chat.AddMessage(sChannel,
                    sUser,
                    TB_ToSend.Text);
                
                TB_ToSend.Text = "";        
            }
        }
    }

When the SEND button is clicked, it calls the function AddMessage that adds a row into the end of the static array.

The page inside the <iframe> tag refreshes every 4 seconds without refreshing your actual page.

Points of Interest

The magic? None, a simple request of the second page into the <iFrame>. So, Internet Explorer takes care of everything for us to read the static array.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Al is just another Software Engineer working in C++, ASp.NET and C#. Enjoys snowboarding in Big Bear, and wait patiently for his daughters to be old enough to write code and snowboard.

Al is a Microsoft ASP.NET MVP

Blog

Comments and Discussions

 
GeneralRe: Cannot open source code Pin
MoustafaS3-May-05 15:07
MoustafaS3-May-05 15:07 
GeneralRe: Cannot open source code Pin
t_t_l5-May-05 3:55
t_t_l5-May-05 3:55 
GeneralRe: Cannot open source code Pin
MoustafaS5-May-05 13:53
MoustafaS5-May-05 13:53 
GeneralRe: Cannot open source code Pin
t_t_l5-May-05 19:48
t_t_l5-May-05 19:48 
GeneralRe: Cannot open source code Pin
Niranjana S19-Jan-07 0:33
Niranjana S19-Jan-07 0:33 
GeneralRe: Cannot open source code Pin
MoustafaS19-Jan-07 23:46
MoustafaS19-Jan-07 23:46 
GeneralIs there anyway to stop screen-flashing Pin
Member 110964021-Jul-04 0:24
Member 110964021-Jul-04 0:24 
GeneralRe: Is there anyway to stop screen-flashing Pin
MaruNYaMan3-Jan-05 10:32
MaruNYaMan3-Jan-05 10:32 
Yes, there is!

We got a solution for 100% pure DHTML chat with no page refreshes and no flicker.

Please try our live demo

and download 30 days free trial.





General Product Features Some of the most important functionality

Moderated Discussions
Chat supports "Moderated Rooms" feature. All the messages in a moderated room are passed through a moderator. A room can have speakers, moderators and regular user roles, each with their specific behavior.

Private Rooms
When a user creates a private room, no other user can enter it, unless they were invited by the room owner.

Private Messages
Also known as whisper. Allows sending a message to a single person only. No other user in the room will see the message.

Ignore Function
Allows ignoring annoying users in a chat room.

Kick and Ban users by name or by IP address
Chat Administrators, Site Administrators and Room Owners can kick users out of the chat. They can also apply ban on user’s name or IP address.

Message font attributes and color
Users can make their message bold italic and underlined and change colors of their messages.

Abusive words filter
Site Administrators can configure a list of words that must NOT appear in the chat. If a user sends a message containing an abusive word his message will be rejected.

Hyperlink aware
Turns certain text patterns, such as www.zbitinc.com or http://chat.zbit.us into HTML hyper-links. The pattern for link conversion is configurable.

Comprehensive Site and Server Administration Interface
Site Administrators can manage all configurations settings of their site as well as rooms users and other options from one convenient location. Server Administrators can manage all the sites and many global chat server parameters.

Canned Messages
Pre-maid messages can be used by support operators to provide instant prompts or answers to common questions.


Customization Create your own look and feel

Fully customizable User Interface
Because UI is implemented as a HTML page it can be easily modified in any HTML or Text Editor. As opposed to Java Applet, Platform-specific Applications or Flash solutions, where the developer of the application controls which attributes of the appearance could be customized, here you can change look and feel entirely by modifying HTML of the pages.

Integration with existing Database
If you would like to integrate chat with your existing user database just import chat tables and stored procedures into your DBMS and then change chat stored procedures to return data from your existing tables.

SDK & Source Code available
For advanced developers Software Development Kit is available that includes un-obfuscated client-side code (JavaScript files) and documentation which describes each communication message and internal plumbing of the application. Server-side source code (C# files) is also available at additional cost.

Multilanguage support
Easily modify the on-screen messages or switch to another natural language all together by modifying strings in existing recourses or creating new resource files.

Character encoding
Typed messages can use character sets with different encodings, displaying eastern European and other encoded sets properly.


Scalability Will fit any environment - Big or Small

Multiple sites on one server
One ASP.NET chat can run multiple independent chat sites. Each site will have its own set of rooms, users, settings and can have customized appearance.

HTTP Tunneling to work through firewalls and proxy servers
Chat works through standard HTTP protocol. There is no need to open any special ports on firewalls or configure proxy servers for the chat to work in corporate environment.

NO ActiveX, Applets and such
The client side of the chat works solely using DHTML. There are NO ActiveX controls, Java Applets, Flash objects or any other embedded active content to be downloaded by the clients – all they need to have is a modern web browser. This makes application more secure and usable on many different platforms, without worrying whether certain virtual machine, framework or platform is installed in a client machine.

X-Copy installation
No setup executables to run. Just follow installation instructions to copy needed files to your virtual directory and configure the application. Great for installing at a shared hosting Internet Service Providers.


Performance Your application will run at top speed

Very fast response time even on a slow connection
Only relevant information is transferred between client browser and the chat sever and only when some action by either side is required, providing for superior performance. No frequent polling is involved.

Highly optimized code
The architecture of the server takes full advantage of multithreaded Microsoft ASP.NET environment and does not waist CPU cycles.

Message Buffering
Messages are bundled together, if possible, so save on unnecessary round trips.


Help & Support We are here to help

User, Site Admin and Server Admin Help
Several Documentation files exist for each type of users, accessible from within chat interface.

Free e-mail support
Pre and post-sale e-mail support is absolutely FREE. You may also contact us via the phone, but due to the volume of calls we ask you to reserve it for urgent situations only and use e-mail when it is possible.

Free Upgrades for life
Buy the product once and receive free upgrades to the same major version as long for as long as they keep on coming. We have a lot of new exciting features that we will add to application and you will not be left behind with the free upgrades.
GeneralRe: Is there anyway to stop screen-flashing Pin
jakesher21-Jun-05 12:02
jakesher21-Jun-05 12:02 
GeneralProblem Opening Project in Visual Studio plz help Pin
'¯`°²¤ zee ¤²°`¯'20-Jun-04 11:15
'¯`°²¤ zee ¤²°`¯'20-Jun-04 11:15 
GeneralRe: Problem Opening Project in Visual Studio plz help Pin
Albert Pascual21-Jun-04 10:51
sitebuilderAlbert Pascual21-Jun-04 10:51 
GeneralHere is another C# chat Pin
Julien Couvreur27-May-04 17:12
Julien Couvreur27-May-04 17:12 
GeneralRe: Here is another C# chat Pin
Albert Pascual27-May-04 18:04
sitebuilderAlbert Pascual27-May-04 18:04 
GeneralRe: Here is another C# chat Pin
FunkyMonkey1-Jun-06 16:41
FunkyMonkey1-Jun-06 16:41 
Generalwhere are the other chat members Pin
Mark Focas27-May-04 15:05
Mark Focas27-May-04 15:05 
GeneralRe: where are the other chat members Pin
Anonymous1-Apr-05 16:58
Anonymous1-Apr-05 16:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.