public static void MarkActivity() { using (var db = new SessionsContext()) { if (db.LastActivity.Count() == 0) { var entity = new LastActivityEntity(); entity.Last = DateTime.Now; db.LastActivity.Add(entity); // First Session var session = new SessionEntity(); session.Start = entity.Last.Value; session.Complete = false; session.End = null; db.Sessions.Add(session); } else { var entity = db.LastActivity.ToList().SingleOrDefault(); var previousTime = entity.Last; entity.Last = DateTime.Now; var delta = (entity.Last.Value - previousTime.Value).TotalMinutes; if (delta >= 15.0) { HandleSession(db, entity.Last.Value, previousTime.Value); } } db.SaveChanges(); } }
public static void HandleSession(SessionsContext db, DateTime latestTime, DateTime previousTime) { // 1) Close incomplete sessions var previousSession = db.Sessions.Where(s => !s.Complete).OrderBy( s => s.End ).ToList().Last(); if (previousSession != null) { previousSession.End = previousTime; previousSession.Complete = true; db.Sessions.Attach(previousSession); } // 2) start new session var session = new SessionEntity(); session.Id = 0; session.Start = latestTime; session.Complete = false; session.End = null; db.Sessions.Add(session); }