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  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
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! Calling all CC Power Users – and those that would like to be!

    Join this Rational Talks to You teleconference, featuring Paul Boustany and Mark Krasovich, to speak to the experts about becoming a Rational ClearCase power user. Get a chance to ask your questions and learn tips and tricks for using Rational ClearCase in Agile development
    FREE! Go There Now!


    NEW! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base.
    FREE! Go There Now!


    NEW! Best Practices in Integrated Requirements Management

    Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right."
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Process

    Visit IBM developerWorks to try the IBM SOA Sandbox for process. The SOA Sandbox for process focuses on providing a trial environment with the necessary tooling and components required to gain a better understanding of business processes and how to best improve existing business processes to derive value quickly.
    FREE! Go There Now!


    NEW! Webcast: Accelerating Software Innovation with System z

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    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...

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT