Exemple #1
0
        private bool ReleaseSessionItemLock(IAspEnvironmentContext context, string sessionid, object lockID)
        {
            string locationID = sessionid;

            try
            {
                _cache.Unlock(locationID, GetUniqueSessionId(sessionid));//, lockID);
                return(true);
            }
            catch (Exception)
            {
                try
                {
                    _cache.Unlock(locationID, GetUniqueSessionId(sessionid));
                    return(true);
                }
                catch (Exception e)
                {
                    if (_detailedLogs)
                    {
                        LogDebug("ReleaseSessionItemLock failed, Exception: " + e.ToString(), sessionid);
                    }
                    LogError(e, sessionid);
                }
            }
            return(false);
        }
Exemple #2
0
        protected override object CreateEmptySession(IAspEnvironmentContext context, int sessionTimeout)
        {
            ISessionStateItemCollection dummyItems = new SessionStateItemCollection();

            dummyItems["session-locked"] = "true";
            return(new SessionStateStoreData(dummyItems, SessionStateUtility.GetSessionStaticObjects(context.Unwrap() as HttpContext), sessionTimeout));
        }
Exemple #3
0
        /**<summary>
         * Inserts item in store.
         * When an items expires, its automatically been removed from cache, so we do not have
         * to check the expiration time, and simply an Insert call to cache will add the items if
         * its new or updates the item if it already exists, so newItem parameter is also useless
         * </summary>**/
        public virtual void SetAndReleaseItemExclusive(IAspEnvironmentContext context, string id, object items, object lockID, bool newItem, int timeout)
        {
            try
            {
                _cache.IsSessionCookieless = IsSessionCookieless(context);
                PutInNCache(context, id, InsertContents(context, items, SessionInitializationActions.None, timeout), lockID, true);
            }
            catch (Exception ex1)
            {
                try
                {
                    if (_cache != null)
                    {
                        string locationID = GetLocationID(context, id);
                        _cache.Remove(locationID, GetUniqueSessionId(id), true);
                    }
                }
                catch (Exception ex2)
                {
                    if (_detailedLogs)
                    {
                        LogDebug("SetAndReleaseItemExclusive failed, Exception:" + ex2, id);
                    }
                }

                try
                {
                    PutInNCache(context, id, InsertContents(context, items, SessionInitializationActions.None, timeout), lockID, false);
                }
                catch (Exception ex3)
                {
                    LogError(ex3, id);
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Extract session data from hastable fetched from cache
        /// </summary>
        /// <param name="context"></param>
        /// <param name="items"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private object GetContents(IAspEnvironmentContext context, Hashtable items, ref SessionInitializationActions flag)
        {
            //int timeout = (int)items[TIMEOUT_KEY];
            flag = (SessionInitializationActions)items[ACTIONS_KEY];
            byte[] buffer  = items[SESSION_DATA] as byte[];
            int    timeout = (int)items[TIMEOUT_KEY];

            return(DeserializeSession(buffer, timeout));

            //SessionStateItemCollection itemsCollection = null;
            //HttpStaticObjectsCollection staticCollection = null;
            //if (items.Contains(ITEMS_KEY))
            //{
            //    itemsCollection = (SessionStateItemCollection)items[ITEMS_KEY];
            //}
            //else
            //{
            //    itemsCollection = new SessionStateItemCollection();
            //}
            //if (items.Contains(STATIC_ITEMS_KEY))
            //{
            //    staticCollection = (HttpStaticObjectsCollection)items[STATIC_ITEMS_KEY];
            //}
            //else
            //{
            //    staticCollection = SessionStateUtility.GetSessionStaticObjects(context);
            //}
            //return new SessionStateStoreData(itemsCollection, staticCollection, timeout);
        }
Exemple #5
0
        protected override object CreateEmptySession(IAspEnvironmentContext context, int sessionTimeout)
        {
            var session = new NCacheSessionData();

            session.Items.Add(NCacheStatics.EmptySessionFlag, null);
            return(session);
        }
Exemple #6
0
        /// <summary>
        /// Extract session data from hastable fetched from cache
        /// </summary>
        /// <param name="context"></param>
        /// <param name="items"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private object GetContents(IAspEnvironmentContext context, Hashtable items, ref SessionInitializationActions flag)
        {
            flag = (SessionInitializationActions)items[ACTIONS_KEY];
            byte[] buffer  = items[SESSION_DATA] as byte[];
            int    timeout = (int)items[TIMEOUT_KEY];

            return(DeserializeSession(buffer, timeout));
        }
Exemple #7
0
        public override object CreateNewStoreData(IAspEnvironmentContext context, int timeOut)
        {
            SessionStateStoreData data = new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context.Unwrap() as HttpContext), timeOut);

            if (_detailedLogs)
            {
                LogDebug("New data object created to be used for current request", null);
            }
            return(data);
        }
Exemple #8
0
        public virtual void ReleaseItemExclusive(IAspEnvironmentContext context, string id, object lockID)
        {
            ///We are using current context items to hold some values. So we have to delete them before
            ///current request completes or is forced to complete.
            context.RemoveItem(SESSION_LOCK_COUNT);

            if (_lockSessions)
            {
                ReleaseSessionItemLock(context, id, lockID);
            }
        }
 /// <summary>
 /// Adds the Current Primary cache's location identifier in the Response cookie collection.
 /// </summary>
 /// <param name="context">Context of current HttpRequest.</param>
 protected void UpdateCookies(IAspEnvironmentContext context)
 {
     if (_cache != null)
     {
         if (!string.IsNullOrEmpty(_cache.PrimaryPrefix))
         {
             context.SetLocationCookie(_cache.PrimaryPrefix);
             if (_logs)
             {
                 LogInfo("Session Location Changed: New_Location=" + _cache.PrimaryPrefix, null);
             }
         }
     }
 }
Exemple #10
0
 /// <summary>
 /// Adds the Current Primary cache's location identifier in the Response cookie collection.
 /// </summary>
 /// <param name="context">Context of current HttpRequest.</param>
 protected void UpdateCookies(IAspEnvironmentContext context)
 {
     if (_cache != null)
     {
         if (!string.IsNullOrEmpty(_cache.PrimaryPrefix))
         {
             context.SetLocationCookie(_cache.PrimaryPrefix);
             //context.Response.Cookies.Set(new HttpCookie(LOC_IDENTIFIER, _cache.PrimaryPrefix));
             if (_logs)
             {
                 LogInfo("Session Location Changed: New_Location=" + _cache.PrimaryPrefix, null);
             }
         }
     }
 }
        /// <summary>
        /// Returns the location identifier for this HttpRequest context. Response cookies are searched first
        /// and if no cookie is found then Requeset cookies are searched for location identifier.
        /// If there isno cookie in Request or Response then the Location Identifier in the SessionId id returned.
        /// </summary>
        /// <param name="context">Context of current HttpRequest</param>
        /// <param name="sessionId">SessionId for the Request</param>
        /// <returns>Location Identifer if cookie is found other wise the sessionId is returned.</returns>
        private string GetLocationID(IAspEnvironmentContext context, string sessionId)
        {
            string locationID = sessionId;

            if (_isLocationAffinityEnabled)
            {
                if (!string.IsNullOrEmpty(locationID = context.GetLocationCookie()))
                {
                    return(locationID);
                }

                return(sessionId);
            }
            return(locationID);
        }
        public virtual void CreateUninitializedItem(IAspEnvironmentContext context, string id, int timeOut)
        {
            try
            {
                _cache.IsSessionCookieless = IsSessionCookieless(context);
                PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, true);
                if (_detailedLogs)
                {
                    LogDebug("New session added to cache.", id);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        string locationID = GetLocationID(context, id);
                        _cache.Remove(locationID, GetUniqueSessionId(id), false);
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    if (_isLocationAffinityEnabled)
                    {
                        UpdateCookies(context);
                    }

                    PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, false);
                    if (_detailedLogs)
                    {
                        LogDebug("New session added to cache.", id);
                    }
                }
                catch (Exception exc)
                {
                    LogError(exc, id);
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Form a hashtable to be added to cache
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <param name="flag"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private Hashtable InsertContents(IAspEnvironmentContext context, object data, SessionInitializationActions flag, int timeout)
        {
            Hashtable items = new Hashtable(4);

            if (data != null)
            {
                byte[] buffer = SerializeSession(data);
                items.Add(SESSION_DATA, buffer);
                items.Add(TIMEOUT_KEY, timeout);
            }
            else
            {
                items.Add(TIMEOUT_KEY, (int)timeout);
            }

            items.Add(ACTIONS_KEY, flag);

            return(items);
        }
Exemple #14
0
        /// <summary>
        /// Form a hashtable to be added to cache
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <param name="flag"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private Hashtable InsertContents(IAspEnvironmentContext context, object data, SessionInitializationActions flag, int timeout)
        {
            Hashtable items = new Hashtable(4);

            if (data != null)
            {
                byte[] buffer = SerializeSession(data);
                items.Add(SESSION_DATA, buffer);
                items.Add(TIMEOUT_KEY, timeout);
            }
            else
            {
                items.Add(TIMEOUT_KEY, (int)timeout);
            }
            //if (data == null)
            //{
            //    items.Add(ITEMS_KEY, new SessionStateItemCollection());
            //    if (context != null)
            //    {
            //        items.Add(STATIC_ITEMS_KEY, SessionStateUtility.GetSessionStaticObjects(context));
            //    }
            //    items.Add(TIMEOUT_KEY, timeout);
            //}
            //else
            //{
            //    if (data.Items != null && data.Items.Count != 0)
            //    {
            //        items.Add(ITEMS_KEY, data.Items);
            //    }
            //    if (data.StaticObjects != null && !data.StaticObjects.NeverAccessed)
            //    {
            //        items.Add(STATIC_ITEMS_KEY, data.StaticObjects);
            //    }
            //    items.Add(TIMEOUT_KEY, data.Timeout);
            //}


            items.Add(ACTIONS_KEY, flag);

            return(items);
        }
Exemple #15
0
 private bool IsSessionCookieless(IAspEnvironmentContext context)
 {
     if (_isLocationAffinityEnabled)
     {
         try
         {
             if (!string.IsNullOrEmpty(context.GetLocationCookie()))
             {
                 return(false);
             }
         }
         catch (Exception e)
         {
             if (NCacheLog != null)
             {
                 LogError(e.ToString(), null);
             }
         }
     }
     return(true);
 }
Exemple #16
0
        /// <summary>
        /// Insert information in cache, along with the expirations and callback.
        /// </summary>
        /// <param name="id">Session ID</param>
        /// <param name="table">Value needed to be stored</param>
        ///
        private void PutInNCache(IAspEnvironmentContext context, string id, Hashtable table, object lockID, bool enableRetry)
        {
            byte[] buffer = null;
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, table);
                buffer = stream.ToArray();
                stream.Close();
            }
            CacheItem sessionItem = new CacheItem(buffer);

            sessionItem.Priority   = CacheItemPriority.NotRemovable;
            sessionItem.Expiration = new Runtime.Caching.Expiration(Runtime.Caching.ExpirationType.Sliding, new TimeSpan(0, (int)table[TIMEOUT_KEY], 0));
            lock (s_dataLock)
            {
                if (s_cacheNeedInit)
                {
                    InitializeCache();
                }
            }

            string locationID = GetLocationID(context, id);

            if (_cache == null)
            {
                LogError(new OperationFailedException("The specified cache is not running. "), id);
                return;
            }

            if (_lockSessions)
            {
                _cache.Insert(locationID, GetUniqueSessionId(id), sessionItem, lockID as LockHandle, true, enableRetry);
            }
            else
            {
                _cache.Insert(locationID, GetUniqueSessionId(id), sessionItem, enableRetry);
            }
            _cache.CurrentSessionCache = null;
        }
        public virtual void CreateUninitializedItem(IAspEnvironmentContext context, string id, int timeOut)
        {
            try
            {
                PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, true);
                if (_detailedLogs)
                {
                    LogDebug("New session added to cache.", id);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        _cache.Remove(GetUniqueSessionId(id), false);
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, false);
                    if (_detailedLogs)
                    {
                        LogDebug("New session added to cache.", id);
                    }
                }
                catch (Exception exc)
                {
                    LogError(exc, id);
                }
            }
        }
Exemple #18
0
 public virtual object GetItemExclusive(IAspEnvironmentContext context, string id, out bool locked, out TimeSpan lockAge, out object lockID, out SessionInitializationActions action)
 {
     return(getSessionStoreItem(_lockSessions, context, id, out locked, out lockAge, out lockID, out action));
 }
Exemple #19
0
        /// <summary>
        /// Returns the location identifier for this HttpRequest context. Response cookies are searched first
        /// and if no cookie is found then Requeset cookies are searched for location identifier.
        /// If there isno cookie in Request or Response then the Location Identifier in the SessionId id returned.
        /// </summary>
        /// <param name="context">Context of current HttpRequest</param>
        /// <param name="sessionId">SessionId for the Request</param>
        /// <returns>Location Identifer if cookie is found other wise the sessionId is returned.</returns>
        private string GetLocationID(IAspEnvironmentContext context, string sessionId)
        {
            string locationID = sessionId;

            return(locationID);
        }
Exemple #20
0
 public override object CreateNewStoreData(IAspEnvironmentContext context, int timeOut)
 {
     return(new NCacheSessionData());
 }
Exemple #21
0
 public virtual object CreateNewStoreData(IAspEnvironmentContext context, int timeOut)
 {
     return(null);
 }
Exemple #22
0
        public virtual void RemoveItem(IAspEnvironmentContext context, string id, object lockID)
        {
            try
            {
                _cache.IsSessionCookieless = IsSessionCookieless(context);
                if (_cache != null)
                {
                    string locationID = GetLocationID(context, id);

                    lock (_cache)
                    {
                        bool removeFromCache = true;
                        if (lockID is LockHandle)
                        {
                            removeFromCache = (((LockHandle)lockID).LockId != null);
                        }

                        if (removeFromCache)
                        {
                            if (_lockSessions)
                            {
                                _cache.Remove(locationID, GetUniqueSessionId(id), lockID as LockHandle, true);
                            }
                            else
                            {
                                _cache.Remove(locationID, GetUniqueSessionId(id), true);
                            }
                        }
                    }
                }
                if (_detailedLogs)
                {
                    LogDebug("Session removed from cache.", id);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        string locationID = GetLocationID(context, id);

                        lock (_cache)
                        {
                            if (_lockSessions)
                            {
                                _cache.Remove(locationID, GetUniqueSessionId(id), lockID as LockHandle, false);
                            }
                            else
                            {
                                _cache.Remove(locationID, GetUniqueSessionId(id), false);
                            }
                        }
                    }

                    if (_detailedLogs)
                    {
                        LogDebug("Session removed from cache. ", id);
                    }
                }
                catch (Exception exc)
                {
                    if (_detailedLogs)
                    {
                        LogDebug("RemoveItem failed, Exception: " + exc.ToString(), id);
                    }
                    LogError(exc, id);
                }
            }
        }
Exemple #23
0
 protected virtual object CreateEmptySession(IAspEnvironmentContext context, int sessionTimeout)
 {
     return(null);
 }
Exemple #24
0
        private object getSessionStoreItem(bool acquireLock, IAspEnvironmentContext context, string id, out bool locked, out TimeSpan lockAge, out object lockID, out SessionInitializationActions action)
        {
            //lock age is set to zero, so SessionStateModule will,
            //after 0.5 sec, calls this GetItemExclusive function until a value or
            //null reference is returned. If no data was found, 'locked' is set to false and
            //null reference is returned which tells SessionStateModule to call CreateDataStore
            //function to create new data store

            locked  = false;
            lockAge = TimeSpan.Zero;
            lockID  = null;
            action  = SessionInitializationActions.InitializeItem;
            DateTime lockDate = DateTime.UtcNow;

            LockHandle lockHandle   = new LockHandle(null, lockDate);
            object     items        = null;
            Hashtable  table        = null;
            bool       lockTimedOut = false;
            string     locationID   = GetLocationID(context, id);


            if (_cache == null)
            {
                LogError(new OperationFailedException("The specified cache is not running. "), id);
                return(null);
            }

            try
            {
                _cache.IsSessionCookieless = IsSessionCookieless(context);
                byte[] buffer = null;
                lock (s_dataLock)
                {
                    if (s_cacheNeedInit)
                    {
                        InitializeCache();
                    }
                }
                if (_lockSessions)
                {
                    try
                    {
                        buffer = (byte[])_cache.Get(locationID, GetUniqueSessionId(id), ref lockHandle, acquireLock, true);
                    }
                    catch (Exception)
                    {
                        buffer = (byte[])_cache.Get(locationID, GetUniqueSessionId(id), ref lockHandle, acquireLock, false);
                    }


                    lockID   = lockHandle.LockId == null ? null : lockHandle;
                    lockDate = lockHandle == null ? DateTime.UtcNow : lockHandle.LockDate;
                }
                else
                {
                    try
                    {
                        buffer = (byte[])_cache.Get(locationID, GetUniqueSessionId(id), true);
                    }
                    catch (Exception)
                    {
                        buffer = (byte[])_cache.Get(locationID, GetUniqueSessionId(id), false);
                    }
                }

                if (buffer != null)
                {
                    using (MemoryStream stream = new MemoryStream(buffer))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        table = formatter.Deserialize(stream) as Hashtable;
                        stream.Close();
                    }
                }

                if (_lockSessions && !String.IsNullOrEmpty(lockHandle.LockId))
                {
                    DateTime now = DateTime.UtcNow;
                    if ((0L < lockDate.Ticks) && (lockDate.Ticks < now.Ticks))
                    {
                        lockAge = (TimeSpan)(now - lockDate);
                    }
                    else
                    {
                        lockAge = TimeSpan.Zero;
                    }

                    /// Following 'if' block is executed if item is locked.
                    /// i.e NCache API returns null and out variables are populated with lockId and lockDate
                    /// Note: Item exists in cache but is locked.
                    if (table == null)
                    {
                        if (this._sessionLockingRetries >= 0)
                        {
                            if (!context.ContainsItem(SESSION_LOCK_COUNT))
                            {
                                context[SESSION_LOCK_COUNT] = 0;
                            }

                            int retriesCompleted = (int)context[SESSION_LOCK_COUNT];

                            if (retriesCompleted < this._sessionLockingRetries)
                            {
                                context[SESSION_LOCK_COUNT] = retriesCompleted + 1;
                            }
                            else ///this will construct and send a dummy session to application
                            {
                                if (this._emptySessionWhenLocked)
                                {
                                    locked       = false;///a dummy session is going to be returned
                                    lockID       = null;
                                    lockTimedOut = true;

                                    return(CreateEmptySession(context, _defaultTimeout));
                                }
                                else
                                {
                                    throw new ProviderException("Cannot acquire session lock. Session is already locked.");
                                }
                            }
                        }

                        locked = true;
                        return(null);
                    }
                }

                /// If item exists in cahce and lock acqusition was successfull or locking was disabled.
                if (table != null)
                {
                    items = GetContents(context, table, ref action);
                    if (action == SessionInitializationActions.InitializeItem)
                    {
                        int timeout = (int)table[TIMEOUT_KEY];
                        items = CreateNewStoreData(context, timeout);
                    }
                }
                else
                {
                    if (NCacheLog != null && NCacheLog.IsInfoEnabled)
                    {
                        NCacheLog.Warn("SessionStoreBase.GetSessionItem", "Session not found in cache. " + id);
                    }
                }
            }
            catch (Exception exc)
            {
                /// If item is not found in Remote cache.
                /// Update cookies to do any further operations for this session request on current primary cache;
                /// and do not raise exception.

                LogError(exc, id);
            }
            finally
            {
                if ((lockTimedOut || table != null) && context.ContainsItem(SESSION_LOCK_COUNT))
                {
                    context.RemoveItem(SESSION_LOCK_COUNT);
                }
                //    throw new ProviderException("Cannot acquire session lock. Session is already locked.");
            }
            return(items);
        }
Exemple #25
0
 public virtual void EndRequest(IAspEnvironmentContext context)
 {
 }
Exemple #26
0
 public virtual void InitializeRequest(IAspEnvironmentContext context)
 {
 }
Exemple #27
0
 public virtual void ResetItemTimeout(IAspEnvironmentContext context, string id)
 {
 }