ASP Code
  Home arrow ASP Code arrow Free Simple Database Driven Chat program b...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP CODE

Free Simple Database Driven Chat program by Adrian Forbes
By: Adrian Forbes
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 22
    2003-01-01

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    I've noticed a few people request to do a chat app from ASP so I've knocked one up. I see you've already got a chat ASP script (from FailSafe),
    Anyway, feel free to add this code straight to your site, it's not that feature rich but it demonstrates the kind of things you need to do. 

    It does not require a login but instead keeps a track of active users based on all the people who have posted within a certain timeframe. There are two options you can configure, how many minutes to keep active users and how many posts to be shown on screen. The main chat area shows you who posted what, at what time and what IP address they posted from, and it also shows a list of active users.   It's nice and simple and includes the code to create the database and I've even commented the page that does all the work (although documentation is not my strong point!)

    Menu.asp

    <%@ Language=VBScript %>
    <HTML>
    <HEAD>
    <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
    </HEAD>
    <BODY>
    <!-- Author: Adrian Forbes -->

    <p>
    <a href="createdb.asp">Create the database</a><br>
    <a href="config.asp">Configure the parameters</a><br>
    <a href="chat.asp">Chat</a><br>
    </p>

    </BODY>
    </HTML>

    CreateDB.ASP

    <%@ Language=VBScript %>
    <HTML>
    <HEAD>
    <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
    </HEAD>
    <BODY>
    <!-- Author: Adrian Forbes -->

    <%
    sConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath ("/examples/test.mdb") & ";"
    set objRS = CreateObject("ADODB.Recordset")
    sSQL = "CREATE TABLE chat (ID int identity, strText memo not null, strUser varchar(50) not null" & _
    sSQL = " strIP varchar(15) not null, dtDatePosted datetime not null)"
    objRS.Open sSQL, sConnect

    sSQL = "CREATE TABLE chatuser (strUser varchar(50) not null, dtLastPosted datetime not null)"
    objRS.Open sSQL, sConnect

    set objRS.ActiveConnection = nothing
    set objRS = nothing

    Application.Lock
    Application("MaxMessages") = 10
    Application("ActiveTime") = 5
    Application.UnLock

    %>

    <p>Database created.</p>
    <p><a href="menu.asp">Back to menu</a></p>
    </BODY>
    </HTML>

    Config.asp

    <%@ Language=VBScript %>
    <%
    sMax = trim(Request.Form("txtMax"))
    sActive = trim(Request.Form("txtActive"))

    if isnumeric(sMax) then
    Application.Lock
    Application("MaxMessages") = Clng(sMax)
    Application.UnLock
    end if

    if isnumeric(sActive) then
    Application.Lock
    Application("ActiveTime") = Clng(sActive)
    Application.UnLock
    end if
    %>
    <HTML>
    <HEAD>
    <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
    </HEAD>
    <BODY>
    <!-- Author: Adrian Forbes -->

    <p>
    <form action="config.asp" method=post>
    <table border=0>
    <tr>
    <td>Max number of messages</td><td><input type=text name=txtMax value="<%=Application("MaxMessages")%>"></td></tr>
    <td>Time to keep users active (mins)</td><td><input type=text name=txtActive value="<%=Application("ActiveTime")%>"></td></tr>
    </table>
    <p><input type=submit value="Save"></p>
    </form>
    </p>
    <p><a href="menu.asp">Back to menu</a></p>
    </BODY>
    </HTML>

    Chat

    <%@ Language=VBScript %>
    <HTML>
    <HEAD>
    <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
    </HEAD>
    <BODY>
    <!-- Author: Adrian Forbes -->

    <p>
    <form action="storechat.asp" method=post>
    You Name:<input type=text name=txtName value="<%=Session("UserName")%>" maxlength=50><br>
    <textarea name=txtChat cols=50 rows=3></textarea>
    <br>
    <input type=submit value="Chat">
    </form>
    </p>
    <p>
    Active users: <select size=1>
    <%
    ' Select the list of users from the ChatUsers table
    set objRS = CreateObject("ADODB.Recordset")
    objRS.Open "SELECT strUser FROM chatuser ORDER BY strUser", 
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath ("/examples/test.mdb") & ";"
    while not objRS.EOF
    Response.Write "<option>" & objRS("strUser") & vbCRLF
    objRS.MoveNext
    wend
    objRS.Close
    %>
    </select>
    </p>

    <p>
    <%
    ' Select each row form the Chat table
    objRS.Open "SELECT strUser, dtDatePosted, strIP, strText FROM chat ORDER BY dtDatePosted DESC"
    while not objRS.EOF
    Response.Write "<p><b>" & objRS("strUser") & "</b> (at <b>" & FormatDateTime(objRS("dtDatePosted"), 3) & _
    "</b> from IP <b>" & objRS("strIP") & "</b>) said<br>" & vbCRLF
    Response.Write replace(server.HTMLEncode(objRS("strText")), vbCRLF, "<br>") & "</p>" & vbCRLF
    objRS.MoveNext
    wend
    objRS.Close
    set objRS.ActiveConnection = nothing
    set objRS = nothing
    %>
    </p>
    </BODY>
    </HTML>

    StoreChat.asp

    <%@ Language=VBScript %>
    <%
    ' Author: Adrian Forbes

    ' This script performs a number of tasks
    ' 1 Add text to the chat table in the database
    ' 2 Maintain the list of active users
    ' 2.1 Check if user is already active (i.e. do they exist in the ChatUsers table)
    ' 2.2 If they are not active (i.e. a new user) then insert their details into the table
    ' 2.3 If they are active update their record to show that they have just posted
    ' 3 Delete excess messages to ensure that only the configured amount are in the chat table

    ' Get the selected usermae
    sUser = trim(Request.Form("txtName"))

    ' Store it in the session
    Session ("UserName") = sUser

    ' Get the chat text
    sText = trim(Request.Form("txtChat"))

    ' if either the username or chat text are blank then redirect back to chat page
    if len(sUser) = 0 or len(sText) = 0 then
    Response.Redirect "chat.asp"
    end if

    ' set up the constants we are using
    adCmdText = 1
    adVarChar = 200
    adDBTimeStamp = 135
    adParamInput = 1

    ' Open our connection, this will be reused throughout

    set objConnect = CreateObject("ADODB.Connection")
    objConnect.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &_
     Server.MapPath ("/examples/test.mdb") & ";"
    objConnect.Open

    ' 1 First of all insert our chat text into the database

    set objCommand = CreateObject("ADODB.Command")
    with objCommand
    set .ActiveConnection = objConnect
    .CommandType = adCmdText
    .CommandText = "insert into chat (strText, strUser, strIP, dtDatePosted) values (?, ?, ?, Now())"
    .Parameters.Append .CreateParameter ("strText", adVarChar, adParamInput, len(sText), sText)
    .Parameters.Append .CreateParameter ("strUser", adVarChar, adParamInput, 50, sUser)
    .Parameters.Append .CreateParameter ("strIP", adVarChar, adParamInput, 15, Request.ServerVariables("REMOTE_ADDR"))
    .Execute
    end with
    set objCommand.ActiveConnection = nothing
    set objCommand = nothing

    ' 2.1 Now we have to find out if this user exists in the chatusers table, i.e. are they
    ' already active?

    set objCommand = CreateObject("ADODB.Command")
    with objCommand
    set .ActiveConnection = objConnect
    .CommandType = adCmdText
    ' This will return how many times they exist in the table. 0 means they are new
    ' 1 means they already exist. A user can't exist more than once in this table
    .CommandText = "select count(*) from ChatUser where strUser = '" & sUser & "'"
    set objRS = .Execute
    if objRS(0) = 0 then
    ' 2.2 count is 0 so we have to add this user to the table
    .CommandText = "insert into ChatUser (strUser, dtLastPosted) values (?, Now())"
    else
    ' 2.3 count is not 0 so update this users entry to show that they have just posted
    .CommandText = "update ChatUser set dtLastPosted = Now() where strUser = ?"
    end if
    .Parameters.Append .CreateParameter ("strUser", adVarChar, adParamInput, 50, sUser)
    .Execute
    end with
    set objCommand.ActiveConnection = nothing
    set objCommand = nothing

    ' Now we want to delete all users in the ChatUser table who have not posted within the
    ' configured time limit

    set objCommand = CreateObject("ADODB.Command")
    with objCommand
    set .ActiveConnection = objConnect
    .CommandType = adCmdText
    ' Use the DateDiff function to delete where the difference between now and when they last
    ' posted is > Application("ActiveTime") minutes
    .CommandText = "delete from ChatUser where DateDiff (""n"", dtLastPosted, Now()) > " & Application("ActiveTime")
    .Execute
    end with
    set objCommand.ActiveConnection = nothing
    set objCommand = nothing

    ' 3 Now we want to delete the excess posts

    set objRS = CreateObject("ADODB.Recordset")
    ' Get a list of all posts in descending order
    objRS.Open "SELECT ID FROM chat ORDER BY dtDatePosted DESC", objConnect

    lID = 0
    i = 0
    bExit = false
    ' Loop through each post
    while not objRS.EOF and not bExit
    i = i + 1
    if i = Clng(Application("MaxMessages")) then
    ' The number of posts is bigger than the cofigured limit of Application("MaxMessages")
    ' Get the ID of this record as we want to delete all others
    lID = objRS("ID")
    bExit = true
    end if
    objRS.MoveNext
    wend

    objRS.Close

    ' Check if lID is > 0, if it is then there were more than the configured limit of
    ' messages
    if lID > 0 then
    ' Delete all messages whose ID is less than this ID as they are too far down the list
    objRS.Open "DELETE FROM chat WHERE ID < " & lID
    end if
    set objRS.ActiveConnection = nothing
    set objRS = nothing

    ' Close our connection
    objConnect.Close
    set objConnect = nothing

    Response.Redirect "chat.asp"
    %>


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP Code Articles
    More By Adrian Forbes

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! Rational Asset Manager eKit

    Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions.
    FREE! Go There Now!


    NEW! Harnessing the power of SQL and Java for high performance data access

    Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services.
    FREE! Go There Now!


    NEW! Cook up Web sites fast with CakePHP, Part 4: Use CakePHP&apos;s Session and Request Handler components

    CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP.
    FREE! Go There Now!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Webcast: WebSphere Process Server

    WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for People

    Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity.
    FREE! Go There Now!


    NEW! Webcast: Eclipse: Empowering the universal platform

    The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP CODE ARTICLES

    - ASP Forms
    - ASP: The Beginning
    - Getting Remote Files With ASP Continued
    - Inbox and Outbox Manipulation in ASP
    - Relational DropDownList Using VB.NET
    - Ad Tracking URL Hits
    - Use ViewState to display one record per page...
    - Send Email using ASP.NET formatted in HTML
    - ASP File Explorer
    - ASP/XML Interview questions by Srivatsan Sri...
    - Various methods of setting Date values to a ...
    - Conditional DataGrid Item and using checkbox...
    - Fill .NET Listbox with SQL DataReader
    - Filling Dropdown box using Code-Behinds in C#
    - FLAMES code sample written in .NET What is F...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek