I am having trouble, I am trying to get updates from a messages table for my web chat. To do this I store the last datetime in a session and try to get messages sent between last datetime and now.
However, it is missing some messages and I cannot figure out why. Is there something wrong with my mysql datetime comparison?
If I refresh the page it resets the session variable and all messages display. In javascript I call the web method every 2 + callback seconds.
private string LastNow
{
get
{
return Session["last_now"] as string ??
(string)(Session["last_now"] = string.Empty);
}
set
{
Session["last_now"] = value;
}
}
[WebMethod(EnableSession=true)]
public object GetMessages(int id, int roomId)
{
string lastDt = LastNow;
/* EDIT */
string now = MySqlHelper.ExecuteScalar(
connstr, "SELECT CAST(NOW() AS CHAR);") as string;
// if the session variable is null or empty,
// get all messages up to now, else most recent
string dtclause =
!string.IsNullOrWhiteSpace(lastDt) ?
string.Format(" AND sent_dt > '{0}' AND sent_dt <= '{1}'", lastDt, now) :
string.Format(" AND sent_dt <= '{0}'", now);
string sql =
string.Format(
"SELECT user_id, type, message FROM Chat.Message WHERE room_id={0}{1};",
roomId, dtclause);
object ret = null;
try // with a finally, always store last update time
{
using (DataSet msgset =
MySqlHelper.ExecuteDataset(Common.SupportDatabase, sql))
{
DataTable msgtable = msgset.Tables[0];
if (msgtable != null)
{
DataRow[] rows = msgtable.Select();
if (rows != null && rows.Length > 0)
{
ret = from msg in rows
select new
{
id = msg["user_id"],
type = msg["type"],
message = msg["message"]
};
}
}
}
}
finally
{
LastNow = now;
}
return ret;
}
There shouldn’t be any reason to do the date parsing in your code. MySQL will already output the
now()function inyyyy-mm-dd hh:mm:ssformat, so just store the raw string that MySQL returns. DateTime parsing will potentially induce things like timezone and daylight savings conversions, which WILL screw up the timstamps. Instead, just suck out the timestamp, and stuff it back in, unconverted.