Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1. INTRODUCTION
‘‘FRIENDS CHAT’’ is complete software for people who want to chat and
make friend. All content stored in database and divided into categories. Categories can be
easily modified to browse and contains a self-organized interface to promote top-stories.
Software can be managed with a role-based system similar like selecting groups etc.
Focus of role-based system to drive applications in secure mode. Content schedule
feature helps you to get music effectively.
The “FRIENDS CHAT” aims at establishing a comprehensive detail for chating.
1.1 Purpose
Today the world totally relay upon the electronic networking to its every day
adventure. People need low communication for communicating with friend far away .
People today need to be updated on daily basis in this competitive world. Most of the
people get the information about the world around through the internet which is fast,
accessible, and reliable. The WWW (World Wide Web) is huge, widely distributed,
global information service centre for Information services: news, advertisements,
consumer information, financial management, education, government, e-commerce.
The Online Chatting site is a secure web environment area deals with relevant
information. It allows a person to chat with other people.
1.2 Scope
Online Chatting is a website with which we can chat with anyone in any part of
the world as long as they are using this website. We can join any group and can talk with
people logged on to that group.
2. MODULE DESCRIPTION
1
Chat Application
Chat Feature
Can chat with people who are logged on and using a group.
Group Feature
Create groups for people of similar interest to chat.
2
Chat Application
CHAPTER III
3. SYSTEM SPECIFICATION
Our project Online Chatting has been developed in C# .Since our project Online
Chatting has been entirely developed by us, the logic or the algorithm used to develop the
project is entirely original.
The front end used in this project for the development of Microsoft is .NET, is a
leading technology platform for delivering business applications. .NET is built on
standard C#, and is designed specifically to cover the needs of business applications.
.NET applications are made up of components. A .NET component is a self-contained
functional software unit that is assembled into a .NET application with its related classes
and files and that communicates with other components.
3
Chat Application
4
Chat Application
The most important language feature added in this version was the introduction of
generics, which are similar in many aspects to C++ templates. This potentially increases
the number of bugs caught at compile time instead of run time by encouraging the use of
strict type checking in areas where it was not possible before. C++ also got a similar
upgrade with the addition of C++/CLI which is slated to replace the use of Managed C++.
Other new features of Visual Studio 2005 include the “Development Designer” which
allows application designs to be validated before deployments, an improved environment
for web publishing when combined with ASP.NET 2.0 and load testing to see application
performance under various sorts of user loads.
5
Chat Application
6
Chat Application
The following illustration shows the relationship of the common language runtime
and the class library to your application and to the overall system. The illustration also
shows how managed code operates with in a larger architecture.
We can use the .NET framework to develop the following types of application
and services:
Console applications
Windows services
The common language runtime (CLR) is responsible for runtime services such as
language integration; security enforcement; and memory process and thread management.
In addition, it has a roll at development time when features such as life cycle
management strong type naming, cross language exception handling, dynamic binding
and so on, reduce the amount of code that a developer must write to turn the business
logic the reusable component. The runtime can be hosted by high performance, server
side applications, such as Microsoft Internet Information Services (IIS) for building web
applications with ASP.Net and the next release of Microsoft SQL Server .This
infrastructure enables you to use code ”managed” by the .NET framework to write your
business logic, while still enjoying the superior performance of the industry’s best
enterprises servers that support runtime hosting.
ASP.NET
7
Chat Application
ADO.NET
ADO.NET Components
There are two components of ADO.NET that you can use to access and
manipulate data:
.NET Framework data Providers
The DataSet
.NET Framework Data Providers
The .Net framework Data Providers are components that have been explicitly
designed for data manipulation and fast, forward-only, read-only access to data. The
Connection object provides connectivity to a data source. The Command object enables
access to database commands to return data, modify data, run stored procedures, and send
or retrieve parameter information. The DataReader provides a high performance stream
of data from the data source. Finally the Data Adapter provides the bridge between the
8
Chat Application
DataSet object and the data source. The Data Adapter object uses the command object to
execute SQL Commands at the data source to both load the DataSet with data, and
reconcile changes made to the data in the DataSet back to the datasource.
The DataSet
The ADO.NET DataSet is explicitly designed for data access independent of any
data source.As a result, it can be used with multiple and differing data sources, used with
XML data, or used to manage data local to the application. The DataSet contains a
collection of one or more DataTable objects made uop of rows and columns of data, as
well as primary key, foreign key, constraint, and relation information about the data in the
DataTable objects.
Benefits of ADO.NET
ADO.NET offers several advantages over previous versions of ADO and over
other data access components. These benefits fall into the following categories:
1. Interoperability
2. Maintainability
3. Programmability
4. Scalability
SQL Server 2005 (codenamed Yukon), released in October 2005, is the successor
to SQL Server 2000. It included native support for managing XMLdata, in addition
to relational data. For this purpose, it defined an xml data type that could be used either as
a data type in database columns or asliterals in queries.
XML columns can be associated with XSD schemas; XML data being stored is
verified against the schema. XML is converted to an internal binary data type before
being stored in the database. Specialized indexing methods were made available for XML
data. XML data is queried using XQuery;CLR Integration was the main features with this
9
Chat Application
edition where one could write SQL code as Managed Code these are those code which
are being executed by CLR(Common Language Runtime).
SQL Server 2005 added some extensions to the T-SQL language to allow
embedding XQuery queries in T-SQL. In addition, it also defines a new extension to
XQuery, called XML DML, which allows query-based modifications to XML data. SQL
Server 2005 also allows a database server to be exposed over web services using TDS
packets encapsulated within SOAP (protocol) requests. When the data is accessed over
web services, results are returned as XML.
For relational data, T-SQL has been augmented with error handling features
(try/catch) and support for recursive queries (Common Table Expressions). SQL Server
2005 has also been enhanced with new indexing algorithms and better error recovery
systems. Data pages are check summed for better error resiliency, and optimistic
concurrency support has been added for better performance. Permissions and access
control have been made more granular and the query processor handles concurrent
execution of queries in a more efficient way. Partitions on tables and indexes are
supported natively, so scaling out a database onto a cluster is easier. SQL CLR was
introduced with SQL Server 2005 to let it integrate with the .NET Framework.
SQL Server 2005 introduced "MARS" (Multiple Active Results Sets), a method of
allowing usage of database connections for multiple purposes.
10
Chat Application
CHAPTER IV
4. SYSTEM ANALYSIS
11
Chat Application
Identification of need
The first step in the system development life cycle is the identification of a
need.To understand the nature of the programs to be built, the analyst must understand
the information domain for the software as well as the required function, performance
and interfacing. Hence the analyst assists the customer in defining the goals of the system
such as what information will be produced, what information is to be provided, what
function and performance are required. The need is to develop a software package.
Preliminary investigation
All the observation is done on the basis of the need of the local
network administrator through Project coordinator and by observing working
existing system.
12
Chat Application
The existing system is a manual system. If the service staff is currently not
available, then there is no way to register our problems. This doesn’t meet the
requirements of the members. During some occasions the member has to wait for a long
time to get connected to the system. Database is less secured and not extensible, the
system lacks some important features.
4.1.1 Drawbacks
The main drawbacks of the existing system are:
There is no way to find whether the friend is currently available or
not.
This system provides only instructions.
It is a slow process.
It is not user friendly.
Managing the data is very difficult.
13
Chat Application
CHAPTER V
5. SYSTEM DESIGN
The user interface design is very important for any application. The
interface design describes how the software communicates within itself, to system that
interpreted with it and with humans who use it. The input design is the process of
converting the user-oriented inputs into the computer-based format. The data is fed into
the system using simple interactive forms. The forms have been supplied with messages
so that user can enter data without facing any difficulty. The data is validated wherever it
requires in the project. This ensures that only the correct data have been incorporated into
the system.
The goal of designing input data is to make the automation as easy and
free from errors as possible. For providing a good input design for the application easy
data input and selection features are adopted. The input design requirements such as user
friendliness, consistent format and Interactive Dialogue for giving the right message and
help for the user at right time are also considered for the development of this project.
14
Chat Application
A quality output is one, which meets the requirements of the end user and
presents the information clearly. In any systems results of processing are communicated
to the user and to other systems through outputs. In the output design it is determined
how the information is to be displayed for immediate need. It is the most important and
direct source information to the user. Efficient and intelligent output design improves the
system’s relationship with the user and helps in decision-making.
The objective of the output Design is to convey the information of all the
past activities, current status and to emphasize important events. The output generally
refers to the results and information that is generated from the system. Outputs from
computers are required primarily to communicate the results of processing to the users.
Output Design Concepts: Output is the most visible component of the information
system.
15
Chat Application
workflow, workflow documentation was designed. Storyboards were created and the
users were asked their suggestion about the visual appearance of the forms.
16
Chat Application
CHAPTER VI
6. IMPLEMENTATION
Introduction
This phase is initiated after the system has been tested and accepted by the
user. In this phase, the system is installed to support the intended business functions.
System performance is compared to performance objectives established during the
planning phase. Implementation includes user notification, user training, installation of
hardware, installation of software onto production computers, and integration of the
system into daily work processes.
Apart from planning major task of preparing the implementation are
education and training of users. The more complex system being implemented, the more
involved will be the system analysis and the design effort required just for
implementation. On implementation coordinating committee based on policies of
individual organization has been appointed.
The implementation process begins with preparing the plan for the
implementation for the system. According to this plan, the activities are to be carried out,
discussion made regarding the equipment and resources and the additional equipment as
to be acquired to implement the new system.
The implementation is the final and important phase. The most critical
stage in achieving successful new system and in giving the user confidence that the new
system will work and be effective. The system can be implemented only after thorough
testing is done and if it found to working according to the specification.
This method also offers the greatest security since the old system can take
over if the errors are found or inability to handle certain type of transaction while using
new system.
17
Chat Application
Implementation Plan
Implementation includes all those activities that take place to convert from
old system to new. At this stage the theoretical design is turned into a working system.
The crucial stage in achieving a successful new system and giving confidence on the
system for the users that will work efficiently and effectively.
The implementation involves careful planning, investigation, of the
current system and its constraints on implementation, design of methods to achieve the
change over. Training of staff in the overall procedures, and evaluation of changeover
methods.
The more complex the system being implemented, the more involved will
be system analysis and design effort required just for implementation.
18
Chat Application
CHAPTER VII
7. SYSTEM TESTING
System testing is an expensive but critical process that can take as much as 50%
of the budget for program development, the common view of testing hold by users that is
performed to prove that there is no error in the program. However, this is virtually
impossible since analysis cannot prove that software is free and clear of errors. Testing is
a process of executing a program with explicit intension of finding errors.
TESTING METHODOLOGIES
System Testing
System testing is the stage of implementation, which is aimed at ensuring that the
system works accurately and efficiently before live operation commences. Testing is vital
to the success of the system. System testing makes a logical assumption that if all the
parts of the system are correct, the goal will be successfully achieved. The candidate
system is subject to a variety of tests:
Recovery Testing: Recovery testing is a system test that forces the software to fail in a
variety of ways and verifies that recovery is properly performed. If recovery is automatic,
re-initialization, check pointing mechanisms, data recovery, and restart are each
evaluated for correctness. If recovery requires human intervention, the mean time to
repair is evaluated to determine whether it is within acceptable limits.
Security Testing : Security testing attempts to verify that protection mechanisms built
into a system will in fact protect it from improper penetration. During security testing, the
tester plays the role of the individual who desires to penetrate the system. The tester may
attempt to acquire passwords through external clerical means, may attack the system with
custom software designed to break down any defenses that have been constructed; may
overwhelm the system, thereby denying service to others; may purposely cause system
19
Chat Application
errors, hoping to penetrate during recovery; may browse through insecure data, hoping to
find the key to system entry; and so on.
Stress Testing: Stress testing executes a system in a manner that demands resources in
abnormal quantity, frequency, or volume. For example,
Special test may be designed that generates 10 interrupts per second, when one or two is
the average rate.
Input data rates may be increased by an order of magnitude to determine how input
functions will respond.
Test cases that require maximum memory or other resources may be executed.
Test case that may cause thrashing in a virtual operating system may be designed.
Test case that may cause excessive hunting for disk resident data may be created.
20
Chat Application
Architectures
Unit testing
Integration testing
Output testing
User acceptance testing
Unit Testing: In unit testing, we have to test the program making up the system. For this
reason, unit testing is sometimes called as program testing. The software units in a system
are the module and routines that are assembled and integrated to perform a specific
function. Unit testing focuses first on the modules independently of one another, to locate
errors. This enables within that module alone.
This testing carried out during programming stage itself. In the testing step, each
module is formed to be working satisfactorily as regards to the expected output from the
module.
21
Chat Application
are easier to isolate and correct; interfaces are more likely to be tested completely; and a
systematic test approach may be applied.
Output Testing: After performing the validation testing, the next step is output testing of
the proposed system since no system could be useful I fit does not produce the required
output in the specific format. The asking the user about the format required by them
tests the outputs generated or displayed by the system under consideration. Here, the
output format is considered into one ways:-is on screen.
The acceptance format on the screen is found to be correct as format was
designed in the system design phase according to the user needs. Hence output
testing does not result in any correction in the system.
User Acceptance Testing: User acceptance testing of a system is the key factor for the
success of any system. The system under consideration is tested for user acceptance by
constantly keeping in touch with the prospective system users at time of developing and
making changes where ever required.
22
Chat Application
CHAPTER VIII
8. IMPLEMENTATION RESULTS
23
Chat Application
- Data Flow
- Process
- Storage
24
Chat Application
Arrows representing the data flows, which can either be electronic data or
physical items.
Open-ended rectangles representing data stores, including electronic stores
such as databases or XML files and physical stores such as or filing cabinets or stacks of
paper.
Data Flow Diagram Layers
Draw data flow diagrams in several nested layers. A single process node on
a high level diagram can be expanded to show a more detailed data flow diagram. Draw
the context diagram first, followed by various layers of data flow diagrams.
Context Diagrams
A context diagram is a top level (also known as Level 0) data flow diagram. It
only contains one process node (process 0) that generalizes the function of the entire
system in relationship to external entities.
25
Chat Application
DFD
Level 0
Context Level
Level 1
User
Level 2 User
26
Chat Application
8.3 CODING
AssemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through
the following
// set of attributes. Change these attribute values to modify the
information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following
four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
27
Chat Application
// You can specify all the values or you can default the Revision
and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use.
Refer to the
// Microsoft .NET Framework documentation for more information on
assembly signing.
//
// Use the attributes below to control which key is used for
signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the
Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file
which contains
// a key.
// (*) If the KeyFile and the KeyName values are both
specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is
used.
// (2) If the KeyName does not exist and the KeyFile does
exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe
(Strong Name) utility.
// When specifying the KeyFile, the location of the
KeyFile should be
// relative to the "project output directory". The
location of the project output
// directory is dependent on whether you are working with
a local or web project.
// For local projects, the project output directory is
defined as
// <Project Directory>\obj\<Configuration>. For example, if
your KeyFile is
// located in the project directory, you would specify the
AssemblyKeyFile
// attribute as [assembly:
AssemblyKeyFile("..\\..\\mykey.snk")]
// For web projects, the project output directory is
defined as
// %HOMEPATH%\VSWebCache\<Machine Name>\<Project
Directory>\obj\<Configuration>.
// (*) Delay Signing is an advanced option - see the
Microsoft .NET Framework
// documentation for more information on this.
//
28
Chat Application
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
Chat Engine.cs
using System;
using System.Threading ;
using System.Web;
using System.Collections;
using System.Collections.Generic ;
using System.Text;
using System.Configuration;
namespace ASPNETChat
/// <summary>
/// The business logic of the chat application
/// </summary>
public static class ChatEngine
{
#region Members
private static Dictionary<string, ChatRoom> Rooms = new
Dictionary<string,
ChatRoom>(Int32.Parse(System.Configuration.ConfigurationManager.A
ppSettings["MaxChatRooms"]));
private static int userChatRoomSessionTimeout =
Int32.Parse(System.Configuration.ConfigurationManager.AppSettings
["UserChatRoomSessionTimeout"]);
#endregion
#region Methods
/// <summary>
/// Cleans all
the chat roomsDeletes the empty chat rooms
/// </summary>
/// <param
name="state"></param>
public static
void CleanChatRooms(object state)
{
lock (Rooms)
{
foreach (object key in Rooms.Keys)
{
ChatRoom room = Rooms[key.ToString()];
room.ExpireUsers(userChatRoomSessionTimeout);
if (room.IsEmpty())
{
room.Dispose();
29
Chat Application
Rooms.Remove(key.ToString());
}
}
}
}
/// <summary>
/// Returns the
chat room for this two users or create a new one if nothing exists
/// </summary>
/// <param
name="user1ID"></param>
/// <param
name="user2ID"></param>
///
<returns></returns>
public static
ChatRoom GetRoom(string roomID)
{
ChatRoom
room=null;
lock (Rooms)
{
if (Rooms.ContainsKey (roomID))
room = Rooms[roomID];
else
{
room = new ChatRoom(roomID);
Rooms.Add(roomID, room);
}
}
return room;
}
/// <summary>
/// Deletes the
specified room
/// </summary>
/// <param
name="roomID"></param>
public static
void DeleteRoom(string roomID)
{
if (!Rooms.ContainsKey(roomID))
return;
lock (Rooms)
{
ChatRoom room = Rooms[roomID];
room.Dispose();
Rooms.Remove(roomID);
}
}
30
Chat Application
#endregion
}
ChatMessages.cs
using System;
namespace ASPNETChat
{
public class Message
{
#region Members
public string
user;
public string msg;
public MsgType
type;
#endregion
#region
Constructors
public
Message(string _user, string _msg, MsgType _type)
{
user =
_user;
msg = _msg;
type =
_type;
}
public
Message(string _user, MsgType _type) : this(_user, "", _type) { }
public
Message(MsgType _type) : this("", "", _type) { }
#endregion
#region Methods
public override
string ToString()
{
switch(this.type)
{
case
MsgType.Msg:
31
Chat Application
case
MsgType.Join :
Chatroom.cs
using System;
using System.Collections ;
using System.Collections.Generic;
namespace ASPNETChat
{
public class ChatRoom : IDisposable
{
#region Members
public
List<Message> messages = null;
public string
RoomID;
private
Dictionary<string,ChatUser> RoomUsers;
private int userChatRoomSessionTimeout;
#endregion
#region
IDisposable Members
public void
Dispose()
{
this.messages.Clear();
this.RoomID="";
32
Chat Application
this.RoomUsers[key.ToString()].Dispose ();
}
#endregion
#region
Constructors
public
ChatRoom(string roomID)
{
this.messages = new List<Message>();
this.RoomID=roomID;
userChatRoomSessionTimeout =
Int32.Parse(System.Configuration.ConfigurationManager.AppSettings
["UserChatRoomSessionTimeout"]);
RoomUsers = new
Dictionary<string,ChatUser>(Int32.Parse(System.Configuration.Conf
igurationManager.AppSettings["ChatRoomMaxUsers"]));
}
#endregion
#region Methods
/// <summary>
/// Returns the
user with the specified id
/// </summary>
/// <param
name="userID"></param>
///
<returns></returns>
public ChatUser
GetUser(string userID)
{
if (!this.RoomUsers.ContainsKey(userID))
return null;
return
this.RoomUsers[userID];
}
/// <summary>
/// Determines if
the room is empty or not
/// </summary>
///
<returns></returns>
public bool
IsEmpty()
{
33
Chat Application
lock(this)
{
if (this.RoomUsers[key.ToString()].IsActive==true)
return false;
}
return true;
}
}
#region
Operations Join,Send,Leave
/// <summary>
/// Marks the
user as inactive
/// </summary>
/// <param
name="userID"></param>
///
<returns></returns>
public void
LeaveRoom(string userID)
{
//deactivat
e user
ChatUser
user=this.GetUser(userID);
if (user == null)
return ;
user.IsActive=false;
user.LastSeen=DateTime.Now;
this.RoomUsers.Remove(userID);
//Add
leaving message
Message msg
= new Message(user.UserName ,"",MsgType.Left);
this.AddMsg(msg);
if (IsEmpty())
ChatEngine.DeleteRoom(this.RoomID);
34
Chat Application
/// <summary>
/// Activates the
user and adds a join message to the room
/// </summary>
/// <param
name="userID"></param>
/// <param
name="userName"></param>
/// <returns>All
the messages sent in the room</returns>
public string
JoinRoom(string userID,string userName)
{
//activate
user
ChatUser
user=new ChatUser(userID,userName);
user.IsActive=true;
user.UserName=userName;
user.LastSeen=DateTime.Now;
if (!
this.RoomUsers.ContainsKey(userID))
{
//Add
join message
this.AddMsg(msg);
//Get
all the messages to the user
int
lastMsgID;
List<Message> previousMessages =
this.GetMessagesSince(-1, out lastMsgID);
user.LastMessageReceived=lastMsgID;
//ret
urn the messages to the user
string str=GenerateMessagesString(previousMessages);
this.RoomUsers.Add(userID,user);
return str;
}
return "";
}
35
Chat Application
/// <summary>
/// Adds a
message in the room
/// </summary>
/// <param
name="strMsg"></param>
/// <param
name="senderID"></param>
/// <returns>All
the messages sent from the other user from the last time the user
sent a message</returns>
public string
SendMessage(string strMsg,string senderID)
{
ChatUser
user=this.GetUser(senderID);
Message
msg=new Message(user.UserName ,strMsg,MsgType.Msg);
user.LastSeen=DateTime.Now;
this.ExpireUsers(userChatRoomSessionTimeout);
this.AddMsg(msg);
int
lastMsgID;
List<Message> previousMsgs =
this.GetMessagesSince(user.LastMessageReceived, out lastMsgID);
if
(lastMsgID!=-1)
user.LastMessageReceived=lastMsgID;
string
res=this.GenerateMessagesString(previousMsgs);
return res;
}
#endregion
/// <summary>
/// Removes the
users that hasn't sent any message during the last window
secondes
/// </summary>
/// <param
name="window">time in secondes</param>
public void
ExpireUsers(int window)
{
try
{
lock (this)
{
foreach (object key in RoomUsers.Keys)
36
Chat Application
{
ChatUser usr =
this.RoomUsers[key.ToString()];
lock (usr)
{
if (usr.LastSeen !=
System.DateTime.MinValue)
{
TimeSpan span = DateTime.Now -
usr.LastSeen;
if (span.TotalSeconds > window &&
usr.IsActive != false)
{
this.LeaveRoom(usr.UserID);
}
}
}
}
}
}
catch
{ }
}
/// <summary>
/// Adds a
message to the room
/// <param
name="msg"></param>
/// <returns> the
id of the new message</returns>
public int
AddMsg(Message msg)
{
int count;
lock(messages)
{
count
= messages.Count;
messages.Add(msg);
}
return
count;
}
/// <summary>
/// Iterates over
the messages array calling ToString() for each message
/// </summary>
37
Chat Application
/// <param
name="msgs"></param>
///
<returns></returns>
private string GenerateMessagesString(List<Message> msgs)
{
string
res="";
for (int
i=0;i<msgs.Count;i++)
{
res+=((Message)msgs[i]).ToString()+"\n";
}
return res;
}
/// <summary>
/// Returns an
array that contains all messages sent after the message with
id=msgid
/// </summary>
/// <param
name="msgid">The id of the message after which all the message
will be retuned </param>
/// <param
name="lastMsgID">the id of the last message returned</param>
///
<returns></returns>
public
List<Message> GetMessagesSince(int msgid,out int lastMsgID)
{
lock(messages)
{
if
((messages.Count) <= (msgid+1))
lastMsgID=-1;
else
lastMsgID=messages.Count-1;
/// <summary>
/// Returns all
the messages sent since the last message the user received
/// </summary>
38
Chat Application
/// <param
name="userID"></param>
///
<returns></returns>
public string
UpdateUser(string userID)
{
ChatUser
user=this.GetUser(userID);
user.LastSeen=DateTime.Now;
this.ExpireUsers(userChatRoomSessionTimeout);
int
lastMsgID;
List<Message> previousMsgs=
this.GetMessagesSince( user.LastMessageReceived,out lastMsgID);
if
(lastMsgID!=-1)
user.LastMessageReceived=lastMsgID;
string
res=this.GenerateMessagesString(previousMsgs);
return res;
}
/// <summary>
/// Returns the names of the users who aer currently in
the rooms
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetRoomUsersNames()
{
ExpireUsers(userChatRoomSessionTimeout);
foreach (object key in RoomUsers.Keys)
{
yield return
this.RoomUsers[key.ToString()].UserName ;
}
#endregion
39
Chat Application
ChatUser.cs
using System;
namespace ASPNETChat
{
public class ChatUser:IDisposable
{
#region Members
public string
UserID;
public string
UserName;
public bool
IsActive;
public DateTime
LastSeen;
public int
LastMessageReceived;
#endregion
#region
Constructors
public
ChatUser(string id,string userName)
{
this.UserID=id;
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
this.UserName=userName;
this.LastMessageReceived=0;
}
#endregion
#region
IDisposable Members
public void
Dispose()
{
this.UserID="";
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
40
Chat Application
this.UserName="";
this.LastMessageReceived=0;
}
#endregion
}
Chat.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using ASPNETChat;
using System.Web.Script.Services;
using System.Web.Script;
using System.Collections;
using System.Collections.Generic;
txtMsg.Attributes.Add("onkeypress", "return
clickButton(event,'btn')");
if (!IsPostBack)
{
hdnRoomID.Value = Request.QueryString["rid"];
ChatRoom room =
ChatEngine.GetRoom(hdnRoomID.Value);
string
41
Chat Application
prevMsgs=room.JoinRoom(Session["UserName"].ToString(),Session["Us
erName"].ToString() );
txt.Text = prevMsgs;
foreach (string s in room.GetRoomUsersNames())
{
lstMembers.Items.Add(new ListItem(s, s));
}
/// <summary>
/// This function is called from the client script
/// </summary>
/// <param name="msg"></param>
/// <param name="roomID"></param>
/// <returns></returns>
[WebMethod]
static public string SendMessage(string msg, string roomID)
{
try
{
ChatRoom room = ChatEngine.GetRoom(roomID);
string res = "";
if (room != null)
{
res = room.SendMessage(msg,
HttpContext.Current.Session["UserName"].ToString());
}
return res;
}
catch (Exception ex)
{
}
return "";
}
/// <summary>
/// This function is called peridically called from the user
to update the messages
/// </summary>
/// <param name="otherUserID"></param>
/// <returns></returns>
[WebMethod]
static public string UpdateUser(string roomID)
{
42
Chat Application
try
{
ChatRoom room = ChatEngine.GetRoom(roomID);
if (room != null)
{
string res = "";
if (room != null)
{
res =
room.UpdateUser(HttpContext.Current.Session["UserName"].ToString(
));
}
return res;
}
}
catch (Exception ex)
{
}
return "";
}
/// <summary>
/// This function is called from the client when the user is
about to leave the room
/// </summary>
/// <param name="otherUser"></param>
/// <returns></returns>
[WebMethod]
static public string LeaveRoom(string roomID)
{
try
{
ChatRoom room = ChatEngine.GetRoom(roomID);
if (room != null)
room.LeaveRoom(HttpContext.Current.Session["UserN
ame"].ToString());
}
catch (Exception ex)
{
}
return "";
}
/// <summary>
/// Returns a comma separated string containing the names of
the users currently online
/// </summary>
/// <param name="roomID"></param>
/// <returns></returns>
[WebMethod]
43
Chat Application
Default.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace UChat.Pages
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data
Source=.\\SQLEXPRESS;AttachDbFilename=|Datadirectory|
44
Chat Application
protected void
Page_Load(object sender, System.EventArgs e)
{
cmd.Connection = con;
if (!IsPostBack == true)
{
}
// Put user
code to initialize the page here
lblErrorMsg.Text = string.Empty;
txtUsername.Attributes.Add("onkeydown",
"if(e
vent.which || event.keyCode){if ((event.which == 13) ||
(event.keyCode == 13))
{document.getElementById('"+btnLogin.UniqueID+"').click();return
false;}} else {return true}; ");
}
protected void
Login( object sender, EventArgs e )
{
cmd.Connection.Close();
cmd.Connection.Open();
cmd.CommandText = "select * from signin where
usrname='" + txtUsername.Text.Trim() + "' and pwd='" +
Textbox1.Text.Trim() + "'";
rdr = cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows == true)
{
rdr.Close();
cmd.Connection.Close();
string user =Textbox1.Text;
Session["channel"] = DropDownList1.SelectedValue;
Session["UserName"] = Textbox1.Text;
Response.Redirect("Chat.aspx?rid=" +
DropDownList1.SelectedValue);
}
else
{
rdr.Close();
cmd.Connection.Close();
msgbox_details("Login Failure");
45
Chat Application
}
public void msgbox_details(string msg)
{
Label lblmsg = new Label();
lblmsg.Text = "<script
language='javascript'>window.alert('" + msg + "')</script>";
Page.Controls.Add(lblmsg);
}
bool
ValidateNick( string nick )
{
if( nick ==
string.Empty )
{
return false;
}
return false;
}
}
return false;
}
return true;
}
#region Web Form
Designer generated code
override
protected void OnInit(EventArgs e)
{
//
46
Chat Application
// 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()
{
}
#endregion
}
}
Signup.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Signup : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data
Source=.\\SQLEXPRESS;AttachDbFilename=|Datadirectory|
chat.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader rdr;
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = con;
Page.Title = "Mail Server";
if (!IsPostBack == true)
{
lblerror.Text = "";
47
Chat Application
}
protected void Button1_Click(object sender, EventArgs e)
{
clear();
}
protected void btnsign_Click(object sender, EventArgs e)
{
cmd.Connection.Close();
cmd.Connection.Open();
cmd.CommandText = "select * from signin where usrname='"+
txtusername.Text.Trim() +"'";
rdr = cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows == true)
{
rdr.Close();
cmd.Connection.Close();
lblerror.Text = "Username already present please
choose another one";
}
else
{
rdr.Close();
cmd.Connection.Close();
cmd.Connection.Open();
cmd.CommandText = "insert into
signin(usrname,pwd,nam,dob,address)values('" +
txtusername.Text.Trim().Replace("'", "''") + "','" +
txtpwd.Text.Trim().Replace("'", "''") + "','" +
txtname.Text.Trim().Replace("'", "''") + "','" +
txtdob.Text.Trim().Replace("'", "''") + "','" +
txtaddress.Text.Trim().Replace("'", "''") + "')";
cmd.ExecuteNonQuery();
cmd.Connection.Close();
ScriptManager.RegisterStartupScript(this,
this.GetType(), "message", "alert('Signup
Successfully');location.href = 'index.aspx';", true);
clear();
}
}
public void clear()
{
txtconfirm.Text = "";
txtname.Text = "";
txtpwd.Text = "";
txtusername.Text = "";
txtaddress.Text = "";
txtdob.Text = "";
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
48
Chat Application
8.4 SCREENSHOTS
Login
Sign in
49
Chat Application
Chatting
50
Chat Application
CHAPTER IX
9. FUTURE ENHANCEMENT
One on One chatting – can include one to one chatting between two people
Friend table-a friends list for each profile
51
Chat Application
CHAPTER X
10. CONCLUSION
52
Chat Application
CHAPTER XI
11. BIBLIOGRAPHY
WEB SITES
www.wikipedia.org
www.msdn.microsoft.com
www.programmersheaven.com
www.codeguruk.com
53