using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections ;
using System.Threading ;
using System.Web;
using System.Diagnostics;
namespace SohoProject
{
//定義了一個結構
public struct User
{
public string name;
public DateTime lasttime;
public DateTime curtime;
public string sessionid;
public string ip;
public string iswhere;
}
public class OnLineUser
{
private static DataTable _alluser;
//唯讀屬性
public DataTable alluser{
get{return _alluser;}
}
public OnLineUser()
{
if(_alluser==null)
{
//define user list
// Declare variables for DataColumn and DataRow objects.
_alluser = new DataTable("onlineuser");
DataColumn myDataColumn;
// Create new DataColumn, set DataType, ColumnName and add to DataTable.
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.String");
myDataColumn.ColumnName = "name";
myDataColumn.AutoIncrement = false;
myDataColumn.Caption = "name";
myDataColumn.ReadOnly = false;
myDataColumn.Unique = false;
_alluser.Columns.Add(myDataColumn);
//功能說明:將目前使用者加入線上列表
//如果該使用者的資料當前仍然在線上列表中,則暫時先不讓該使用者登陸,提示使用者存在
public bool AddUserToOnLine(User user)
{
#if DEBUG
(new SohoProject.SohoDebug()).WriteToDoc("開始進入<將目前使用者加入線上列表>....");
(new SohoProject.SohoDebug()).WriteToDoc("\r\n");
#endif
//開始搜尋是否已經存在該使用者,如果存在則是改變資料,否則添加新的使用者
string strExpr;
strExpr = "sessionid='" + user.sessionid + "'";
DataRow[] curUser;
// Use the Select method to find all rows matching the filter.
#if DEBUG
(new SohoProject.SohoDebug()).WriteToDoc("搜尋字串:" + strExpr);
(new SohoProject.SohoDebug()).WriteToDoc("\r\n");
#endif
curUser = _alluser.Select(strExpr);
#if DEBUG
(new SohoProject.SohoDebug()).WriteToDoc(strExpr);
(new SohoProject.SohoDebug()).WriteToDoc(curUser.Length.ToString());
#endif
if (curUser.Length >0 )
{
for(int i = 0; i < curUser.Length; i ++)
{
curUser[i]["curtime"]=DateTime.Now;
curUser[i]["iswhere"]=user.iswhere;
}
}
else
{
//直接加入新的資料
DataRow myRow;
try
{
myRow = _alluser.NewRow();
// Then add the new row to the collection.
myRow["name"] = user.name;
myRow["ip"] = user.ip;
myRow["iswhere"] = user.iswhere;
myRow["lasttime"] = user.lasttime;
myRow["curtime"] = DateTime.Now;
myRow["sessionid"] = user.sessionid;
_alluser.Rows.Add(myRow);
}
catch(Exception e)
{
throw(new Exception(e + "--------------------" + e.ToString())) ;
}
}
_alluser.AcceptChanges();
return true;
}
//功能說明:判斷某使用者是否線上,本部分暫時不用
//傳回值:TRUE代表線上,FALSE不在
public Boolean IsUserOnLine(string name)
{
//需要先判斷使用者是否已經在使用者列表中了
//開始搜尋是否已經存在該使用者,如果存在則是改變資料,否則添加新的使用者
string strExpr;
strExpr = "name ='" + name + "'";
DataRow[] curUser;
// Use the Select method to find all rows matching the filter.
curUser = _alluser.Select(strExpr);
//OnLineUser alluser= new OnLineUser();
AddUserToOnLine(newuser);
}
return(false);
}
}
/*
下面開始建立守護線程類:
(註:此處,開始寫的時候本來想做成單件模式的,不過由於以前沒有做過這個東西,所以反而發生
了很多問題,最後決定放棄而使用現有的格式)
*/
public class CheckOnline
{
const int DELAY_TIMES = 10000 ; //定義執行的時間間隔為5秒
const int DELAY_SECONDS=60; //將使用者掉線時間設定為30秒