/// <summary>
 ///     Initialize new session and adds it to the dictionary
 /// </summary>
 /// <param name="request">Input request</param>
 /// <param name="key">SessionContext key (GUID or existing session key)</param>
 /// <param name="cookieExists">Defines wheter cookie set on client or not</param>
 private void InitNewSession(IRequest request, string key, bool cookieExists = false)
 {
     var session = new SessionContext(key, DateTime.Now + SessionLifeTime) { CookieExist = cookieExists };
     session.ContextChanged += SessionOnContextChanged;
     SaveSession(request.UnitOfWork, session);
     RegisterSession(request, session);
 }
        private void SaveSession(UnitOfWork unit, SessionContext sessionContext)
        {
            var encryptedData = StringCipher.Encrypt(sessionContext.Serialize(), Settings.Default.Secret);

            unit.Sessions.Save(new Session()
            {
                Key = sessionContext.Key,
                Expires = sessionContext.Expires,
                Data = encryptedData
            });
        }
        private SessionContext LoadSession(UnitOfWork unit, string key)
        {
            var existingSession = unit.Sessions.FindById(key);
            if (existingSession != null)
            {
                // If session expired
                if (DateTime.Now > existingSession.Expires)
                {
                    unit.Sessions.Delete(existingSession);
                    return null;
                }
                var sessionContext = new SessionContext(existingSession.Key, existingSession.Expires);
                sessionContext.ContextChanged += SessionOnContextChanged;

                var data = StringCipher.Decrypt(existingSession.Data, Settings.Default.Secret);
                sessionContext.Deserialize(data);
                return sessionContext;
            }
            return null;
        }
 private void RegisterSession(IRequest request, SessionContext session)
 {
     _sessions.Add(session.Key, session);
     request.Session = session;
 }