Click here to Skip to main content
6,635,160 members and growing! (16,695 online)
Email Password   helpLost your password?
Web Development » Applications & Tools » Applications     Intermediate

Simple chat application for ASP.NET

By Albert Pascual

Very easy Web application of a chat room for Internet Explorer 5+ in ASP.NET.
.NET, Win2K, WinXP, Win2003, ASP.NET, Visual Studio, Dev
Posted:26 May 2004
Views:229,552
Bookmarked:114 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
53 votes for this article.
Popularity: 7.59 Rating: 4.40 out of 5
3 votes, 5.7%
1
1 vote, 1.9%
2
5 votes, 9.4%
3
10 votes, 18.9%
4
34 votes, 64.2%
5

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:

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:

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

About the Author

Albert Pascual


Member
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
Occupation: Web Developer
Location: United States United States

Other popular Applications & Tools articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh)FirstPrevNext
GeneralNot Single Author Uploading The Real Application Code Pinmemberajay_zenta7:56 14 Aug '09  
GeneralChat Application Pinmembershangi_13:01 23 Jul '09  
Generalmultiple user Pinmembermani_ascent3:52 7 Jan '09  
Generalthank u Pinmemberphaninderp4:23 12 Oct '08  
Generalhi PinmemberRAHULPANDARE20:57 17 Sep '08  
Generalhai PinmemberMember 447717421:15 28 Aug '08  
Generalhai i want to add multiple chat rooms PinmemberMember 447717421:26 28 Aug '08  
GeneralHow to add the new chat rooms.. Pinmemberdesigank20:47 26 Aug '08  
QuestionChat Feature Pinmemberer.piyushverma073:13 3 Jul '08  
Generalusing database Pinmemberdigdem11:01 3 Jun '08  
GeneralRe: using database Pinmemberdesigank20:50 26 Aug '08  
GeneralSimJax.. Pinmemberbeodd19:44 7 Mar '08  
Questioninternal search engine code Pinmemberumesh1234560:31 23 Oct '07  
Generalonline chat Pinmemberneha mathur8:04 5 Jul '07  
Generali want simple chat application in asp.net using vb Pinmemberkarthikeyan_caleb20:05 16 Apr '07  
Generalplease... Pinmemberchoorakkuttyil22:03 22 Mar '07  
GeneralRe: please... PinmemberMoh.Shafe3i2:10 31 Mar '08  
Generalusing chat On PCs connected with Lan Pinmemberniting8520:00 20 Mar '07  
Generalabout chat Pinmemberrajakvl200421:40 19 Dec '06  
Generalworking with vwd2005 chat not in C# code Pinmemberbernie_01121:18 24 Oct '06  
GeneralHi Albert Pascual, I have 2 doubts Pinmemberrajasekarbtech4:47 12 Sep '06  
GeneralRe: Hi Albert Pascual, I have 2 doubts Pinmemberlittleheartzzz2:56 19 Dec '06  
Questionhi Pinmemberrenatofixer14:02 21 Aug '06  
Questionhow to show that the user is online Pinmemberjasine18:33 7 Aug '06  
GeneralHey Al...Problem with coding Pinmemberlehya9:02 9 Jul '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 May 2004
Editor: Smitha Vijayan
Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project