/// <summary> /// Add session to cache /// </summary> /// <param name="sess"></param> public void AddSession(Session sess) { Cache_Lock.EnterWriteLock(); try { if (!Cache.ContainsKey(sess.SessionGuid)) { Cache.Add(sess.SessionGuid, sess); } } finally { Cache_Lock.ExitWriteLock(); } }
/// <summary> /// Create session for user /// </summary> /// <param name="user_id"></param> /// <returns></returns> public static Session CreateSession(long user_id) { using (var dbx = new SessionsContainer()) { var ts = DateTime.Now; var sqlite_guid = Guid.NewGuid().ToString(); var sess = new Session() { Id = sqlite_guid, UserId = user_id, Created = ts, LastActivity = ts }; dbx.Session.Add(sess); dbx.SaveChanges(); sess = dbx.Session .Include(s => s.User.Role) .Where(s => s.Id == sqlite_guid).First(); return sess; } }
/// <summary> /// Update sessions activity /// if <see cref="Session.IsActivityUpdateRequired">required</see> /// </summary> /// <param name="sessions"></param> public static void UpdateActivity(Session[] sessions) { foreach (var sess in sessions) { if (sess.IsActivityUpdateRequired) { try { using (var dbx = new SessionsContainer()) { var sqlite_guid = sess.SessionGuid.ToString(); var db_sess = dbx.Session.Where( s => s.Id == sqlite_guid).FirstOrDefault(); if (db_sess == null) continue; db_sess.LastActivity = DateTime.Now; dbx.SaveChanges(); } } catch (DbUpdateConcurrencyException cex) { // session was removed var hres = cex.HResult; Console.WriteLine("DbUpdateConcurrencyException on " + sess.ToString()); } } } }
/// <summary> /// BL: Create Session /// </summary> /// <param name="user_id"></param> /// <returns></returns> public Session CreateSession(long user_id) { var ts = DateTime.Now; var sqlite_guid = Guid.NewGuid().ToString(); var sess = new Session() { Id = sqlite_guid, UserId = user_id, Created = ts, LastActivity = ts }; // put request: session record create StorageManager.UpdateAsync((dbx) => { dbx.Session.Add(sess); }, "Create Session"); //put request: get created session with user and roles // (waiting for create because it in front of the requests queue) sess = StorageManager.Get<Session>((dbx) => { return dbx.Session .Include(s => s.User.Role) .Where(s => s.Id == sqlite_guid).First(); }, "Get New Session"); Data_Lock.EnterWriteLock(); try { Data.Add(sess.SessionGuid, sess); } finally { Data_Lock.ExitWriteLock(); } return sess; }