public void Save(ISessionStateContext context, IDictionary<string, object> values)
 {
     EnsureInitialized(context);
     var sessionState = new SessionStateStoreData(new SessionStateItemCollection().AddItems(values), new HttpStaticObjectsCollection(), _timeout);
     var data = new SessionStateEncoding().Serialize(sessionState);
     _sessionStore.Save(SqlSessionId.Create(context.MetabasePath, context.SessionId), data);
 }
        public void GetItemExclusive_RecordFound()
        {
            Utility.SetConfigUtilityToDefault();
            string id = "session-id";
            bool locked;
            TimeSpan lockAge;
            object lockId = null;
            SessionStateActions actions;

            ISessionStateItemCollection sessionStateItemCollection = new ChangeTrackingSessionStateItemCollection();
            sessionStateItemCollection["session-key"] = "session-value";
            SessionStateStoreData sssd = new SessionStateStoreData(sessionStateItemCollection, null, 15);

            ISessionStateItemCollection sessionData = new ChangeTrackingSessionStateItemCollection();
            sessionData["session-key"] = "session-value";

            ISessionStateItemCollection mockSessionData = null;
            object mockLockId = 0;
            int mockSessionTimeout;
            int sessionTimeout = (int)RedisSessionStateProvider.configuration.SessionTimeout.TotalMinutes;
            var mockCache = A.Fake<ICacheConnection>();
            A.CallTo(() => mockCache.TryTakeWriteLockAndGetData(A<DateTime>.Ignored, 90, out mockLockId, out mockSessionData, out mockSessionTimeout)).Returns(true).AssignsOutAndRefParameters(0, sessionData, (int)RedisSessionStateProvider.configuration.SessionTimeout.TotalMinutes);

            RedisSessionStateProvider sessionStateStore = new RedisSessionStateProvider();
            sessionStateStore.cache = mockCache;
            SessionStateStoreData sessionStateStoreData = sessionStateStore.GetItemExclusive(null, id, out locked, out lockAge, out lockId, out actions);
            A.CallTo(() => mockCache.TryTakeWriteLockAndGetData(A<DateTime>.Ignored, 90, out mockLockId, out sessionData, out sessionTimeout)).MustHaveHappened();

            Assert.Equal(true, Utility.CompareSessionStateStoreData(sessionStateStoreData, sssd));
            Assert.Equal(false, locked);
            Assert.Equal(TimeSpan.Zero, lockAge);
            Assert.Equal(actions, SessionStateActions.None);
        }
 public void CreateNewStoreData_WithEmptyStore()
 {
     Utility.SetConfigUtilityToDefault();
     SessionStateStoreData sssd = new SessionStateStoreData(new ChangeTrackingSessionStateItemCollection(), null, 900);
     RedisSessionStateProvider sessionStateStore = new RedisSessionStateProvider();
     Assert.Equal(true, Utility.CompareSessionStateStoreData(sessionStateStore.CreateNewStoreData(null, 900),sssd));
 }
        public void SetAndReleaseItem(System.Web.HttpContext context, string id, System.Web.SessionState.SessionStateStoreData item, object lockId, bool newItem)
        {
            MemcachedSessionDo session;

            if (newItem)
            {
                session = new MemcachedSessionDo()
                {
                    Created         = DateTime.Now,
                    ApplicationName = "",
                    Locked          = false,
                    LockId          = 0,
                    Flags           = (Int32)SessionStateActions.None,
                    LockDate        = DateTime.Now,
                    SessionItem     = Serialize((SessionStateItemCollection)item.Items),
                };
                client.Store(StoreMode.Set, id, session, DateTime.Now.AddMinutes(sessionStateSection.Timeout.TotalMinutes));
            }
            else
            {
                session = client.Get <MemcachedSessionDo>(id);
                if (session != null)
                {
                    session.Locked      = false;
                    session.SessionItem = Serialize((SessionStateItemCollection)item.Items);
                    client.Store(StoreMode.Set, id, session, DateTime.Now.AddMinutes(sessionStateSection.Timeout.TotalMinutes));
                }
            }
        }
        internal static bool CompareSessionStateStoreData(SessionStateStoreData obj1, SessionStateStoreData obj2)
        {
            if ((obj1 == null && obj2 != null) || (obj1 != null && obj2 == null))
            {
                return false;
            }
            else if (obj1 != null && obj2 != null)
            {
                if (obj1.Timeout != obj2.Timeout)
                {
                    return false;
                }

                System.Collections.Specialized.NameObjectCollectionBase.KeysCollection keys1 = obj1.Items.Keys;
                System.Collections.Specialized.NameObjectCollectionBase.KeysCollection keys2 = obj2.Items.Keys;

                if ((keys1 != null && keys2 == null) || (keys1 == null && keys2 != null))
                {
                    return false;
                }
                else if (keys1 != null && keys2 != null)
                {
                    foreach (string key in keys1)
                    {
                        if (obj2.Items[key] == null)
                        {
                            return false;
                        }
                    }
                }

            }
            return true;
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            var sessionStore = SessionStore.Instance;
            try
            {

                byte[] serializedItems = Serialize((SessionStateItemCollection)item.Items);
                Binary sessionItems = new Binary(serializedItems);

                if (newItem)
                {
                    // Delete an existing expired session if it exists.
                    sessionStore.EvictExpiredSession(id, _applicationName);

                    // insert new session item.
                    Session session = new Session(id, this._applicationName, item.Timeout, sessionItems, item.Items.Count, 0);
                    sessionStore.Insert(session);
                }
                else
                {
                    sessionStore.UpdateSession(id, item.Timeout, sessionItems, this._applicationName, item.Items.Count, lockId);
                }
            }
            catch (Exception e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "SetAndReleaseItemExclusive");
                    throw new ProviderException(e.Message, e.InnerException);
                }
                else
                    throw e;
            }
        }
        /// <summary>
        /// Called when SessionState = ReadOnly
        /// </summary>
        public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
        {
            RedisConnection redisConnection = ConnectionUtils.Connect("10.0.0.3:6379");
            {
                redisConnection.Open();

                var result = redisConnection.Strings.Get(0, id);
                byte[] raw = redisConnection.Wait(result);

                actions = SessionStateActions.None;

                SessionEntity sessionEntity = GetFromBytes(raw);
                if (sessionEntity == null || sessionEntity.SessionItems == null )
                {
                    locked = false;
                    lockId = _lock;
                    lockAge = TimeSpan.MinValue;
                    return null;
                }

                ISessionStateItemCollection sessionItems = new SessionStateItemCollection();
                foreach (string key in sessionEntity.SessionItems.Keys)
                {
                    sessionItems[key] = sessionEntity.SessionItems[key];
                }

                SessionStateStoreData data = new SessionStateStoreData(sessionItems, _staticObjects, context.Session.Timeout);

                locked = false;
                lockId = _lock;
                lockAge = TimeSpan.MinValue;
                return data;
            }
        }
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     var sessionItems = new SessionStateItemCollection();
     string sessionString = JsonConvert.SerializeObject(sessionItems);
     cache.PutAsync(context.Session.SessionID, sessionString, TimeSpan.FromMinutes(timeout));
     var data = new SessionStateStoreData(sessionItems, null, timeout);
     return data;
 }
 public void SetUp()
 {
     var configure = new MongoConfigurationBuilder();
     configure.ConnectionStringAppSettingKey("mongoserver");
     config = configure.BuildConfiguration();
     SessionStateItemCollection sessionItemsCollection = new SessionStateItemCollection();
     HttpStaticObjectsCollection staticObjectsCollection = new HttpStaticObjectsCollection();
     item = new SessionStateStoreData(sessionItemsCollection, staticObjectsCollection, 1);
 }
        /// <summary>
        /// Creates a new System.Web.SessionState.SessionStateStoreData object to be
        /// used for the current request.
        /// </summary>
        /// <param name="context">The current request context</param>
        /// <param name="timeout">The session-state System.Web.SessionState.HttpSessionState.Timeout value
        /// for the new System.Web.SessionState.SessionStateStoreData.</param>
        /// <returns>A new System.Web.SessionState.SessionStateStoreData for the current request.</returns>
        public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
        {
            SessionStateStoreData data = new SessionStateStoreData(
                new SessionStateItemCollection(),
                SessionStateUtility.GetSessionStaticObjects(context),
                timeout);

            return data;
        }
 public void Should_Encode_Session_Data()
 {
     var encoding = new SessionStateEncoding();
     var sessionState = new SessionStateStoreData(new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20);
     sessionState.Items[Constants.SessionStateKey1] = Constants.SessionStateValue1;
     sessionState.Items[Constants.SessionStateKey2] = Constants.SessionStateValue2;
     sessionState.Items[Constants.SessionStateKey3] = Constants.SessionStateValue3;
     encoding.Serialize(sessionState).SequenceEqual(Constants.SessionStateSerializedBytes).ShouldBeTrue();
 }
        public RedisASPSessionVariantDictionary Init(RedisASPSessionStateProvider sessionProvider, SessionStateStoreData storeData, string sessionId, int expiry)
        {
            //PFSession.Log.Debug($"PFRedisVariantDictionary:Init:{hashkey}");
            //System.IO.File.AppendAllText(@"C:\\log files\\pfsession.log", $"PFRedisVariantDictionary:Init:{hashkey}");
            this.sessionId = sessionId;
            this.sessionProvider = sessionProvider;
            this.storeData = storeData;

            return this;
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            ISessionStateItemCollection sessionItems = null;
            HttpStaticObjectsCollection staticObjects = null;

            if (item.Items.Count > 0)
                sessionItems = item.Items;
            if (!item.StaticObjects.NeverAccessed)
                staticObjects = item.StaticObjects;

            RedisSessionState state2 = new RedisSessionState(sessionItems, staticObjects, item.Timeout);
            RedisHelper.Set<string>(id, state2.ToJson(), DateTime.Now.AddHours(1));
        }
 internal void RaiseSessionOnEnd(string id, SessionStateStoreData item)
 {
     HttpSessionStateContainer container = new HttpSessionStateContainer(id, item.Items, item.StaticObjects, item.Timeout, false, SessionStateModule.s_configCookieless, SessionStateModule.s_configMode, true);
     HttpSessionState sessionState = new HttpSessionState(container);
     if (HttpRuntime.ShutdownInProgress)
     {
         this.RaiseOnEnd(sessionState);
     }
     else
     {
         SessionOnEndTargetWorkItem item2 = new SessionOnEndTargetWorkItem(this, sessionState);
         WorkItem.PostInternal(new WorkItemCallback(item2.RaiseOnEndCallback));
     }
 }
 public byte[] Serialize(SessionStateStoreData sessionState)
 {
     var hasItems = sessionState.Items != null && sessionState.Items.Count > 0;
     var hasStaticObjects = sessionState.StaticObjects != null && !sessionState.StaticObjects.NeverAccessed;
     var stream = new MemoryStream();
     var writer = new BinaryWriter(stream);
     writer.Write(sessionState.Timeout);
     writer.Write(hasItems);
     writer.Write(hasStaticObjects);
     if (hasItems) ((SessionStateItemCollection)sessionState.Items).Serialize(writer);
     if (hasStaticObjects) sessionState.StaticObjects.Serialize(writer);
     writer.Write(byte.MaxValue);
     return stream.ToArray();
 }
        /// <summary>
        /// Deserializes a base 64 string to a SessionStateStoreData object.
        /// </summary>
        /// <param name="base64String">The base64 string.</param>
        /// <param name="context">The context.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns></returns>
        public static SessionStateStoreData DeserializeToSessionStateStoreData(this string base64String, HttpContext context, int timeout)
        {
            using (var memoryStream = new MemoryStream(Convert.FromBase64String(base64String)))
            {
                var sessionItems = new SessionStateItemCollection();
                if (memoryStream.Length > 0)
                {
                    using (var reader = new BinaryReader(memoryStream))
                    {
                        sessionItems = SessionStateItemCollection.Deserialize(reader);
                    }
                }

                var sessionStateStoreData = new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout);
                return sessionStateStoreData;
            }
        }
 public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked,
     out TimeSpan lockAge, out object lockId,
     out SessionStateActions actions)
 {
     // set default out parameters
     locked = false;
     lockAge = new TimeSpan();
     lockId = null;
     actions = SessionStateActions.None;
     // try to get the session from cache.
     string sessionString = cache.GetAsync<string>(id).Result;
     if (string.IsNullOrEmpty(sessionString))
         return null;
     var sessionItems = JsonConvert.DeserializeObject<SessionStateItemCollection>(sessionString);
     var data = new SessionStateStoreData(sessionItems, null, 60); // todo: set timeout.
     return data;
 }
Ejemplo n.º 18
0
        HttpSessionStateContainer CreateContainer(string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly)
        {
            if (data == null)
            {
                return(new HttpSessionStateContainer(
                           sessionId, null, null, 0, isNew,
                           config.Cookieless, config.Mode, isReadOnly));
            }

            return(new HttpSessionStateContainer(
                       sessionId,
                       data.Items,
                       data.StaticObjects,
                       data.Timeout,
                       isNew,
                       config.Cookieless,
                       config.Mode,
                       isReadOnly));
        }
Ejemplo n.º 19
0
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        String id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buf;
            int    length;
            int    lockCookie;

            Debug.Assert(item.Items != null, "item.Items != null");
            Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");

            Debug.Trace("OutOfProcSessionStateStore", "Calling Set, id=" + id + " sessionItems=" + item.Items + " timeout=" + item.Timeout);

            try {
                SessionStateUtility.SerializeStoreData(item, 0, out buf, out length, s_configCompressionEnabled);
            }
            catch {
                if (!newItem)
                {
                    ((SessionStateStoreProviderBase)this).ReleaseItemExclusive(context, id, lockId);
                }
                throw;
            }

            // Save it to the store

            if (lockId == null)
            {
                lockCookie = 0;
            }
            else
            {
                lockCookie = (int)lockId;
            }

            MakeRequest(UnsafeNativeMethods.StateProtocolVerb.PUT, id,
                        UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, item.Timeout, lockCookie,
                        buf, length, s_networkTimeout, out results);
        }
 internal static void SerializeStoreData(SessionStateStoreData item, int initialStreamSize, out byte[] buf, out int length, bool compressionEnabled)
 {
     using (MemoryStream stream = new MemoryStream(initialStreamSize))
     {
         Serialize(item, stream);
         if (compressionEnabled)
         {
             byte[] buffer = stream.GetBuffer();
             int    count  = (int)stream.Length;
             stream.SetLength(0L);
             using (DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Compress, true))
             {
                 stream2.Write(buffer, 0, count);
             }
             stream.WriteByte(0xff);
         }
         buf    = stream.GetBuffer();
         length = (int)stream.Length;
     }
 }
Ejemplo n.º 21
0
        void WaitForStoreUnlock(HttpContext context, string sessionId, bool isReadOnly)
        {
            DateTime dt = DateTime.Now;

            while ((DateTime.Now - dt) < executionTimeout)
            {
                Thread.Sleep(500);
                storeData = GetStoreData(context, sessionId, isReadOnly);
                if (storeData == null && storeLocked && (storeLockAge > executionTimeout))
                {
                    handler.ReleaseItemExclusive(context, sessionId, storeLockId);
                    return;
                }
                else if (storeData != null && !storeLocked)
                {
                    //we have the session
                    return;
                }
            }
        }
        // Remove an item.  Note that the item is originally obtained by GetExclusive
        // Same note as Set on lockId
        public override void RemoveItem(HttpContext context,
                                        String id,
                                        object lockId,
                                        SessionStateStoreData item)
        {
            Debug.Assert(lockId != null, "lockId != null");

            string        key           = CreateSessionStateCacheKey(id);
            CacheInternal cacheInternal = HttpRuntime.CacheInternal;
            int           lockCookie    = (int)lockId;

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            InProcSessionState state = (InProcSessionState)cacheInternal.Get(key);

            /* If the item isn't there, we probably took too long to run. */
            if (state == null)
            {
                return;
            }

            state._spinLock.AcquireWriterLock();

            try {
                /* Only remove the item if we are the owner */
                if (!state._locked || state._lockCookie != lockCookie)
                {
                    return;
                }

                /* prevent overwriting when we drop the lock */
                state._lockCookie = 0;
            }
            finally {
                state._spinLock.ReleaseWriterLock();
            }

            cacheInternal.Remove(key);

            TraceSessionStats();
        }
Ejemplo n.º 23
0
 void GetStoreData(HttpContext context, string sessionId, bool isReadOnly)
 {
     storeData = (isReadOnly) ?
                 handler.GetItem(context,
                                 sessionId,
                                 out storeLocked,
                                 out storeLockAge,
                                 out storeLockId,
                                 out storeSessionAction)
             :
                 handler.GetItemExclusive(context,
                                          sessionId,
                                          out storeLocked,
                                          out storeLockAge,
                                          out storeLockId,
                                          out storeSessionAction);
     if (storeLockId == null)
     {
         storeLockId = 0;
     }
 }
Ejemplo n.º 24
0
        public static byte[] Serialize(SessionStateStoreData sessionData)
        {
            byte sessionFlag = 0;
            MemoryStream stream = null;
            byte[] buffer = null;
            try
            {
                stream = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stream);

                if (sessionData.Items != null)
                {
                    sessionFlag = (byte)(sessionFlag | SESSION_ITEMS);
                }
                if (sessionData.StaticObjects != null && !sessionData.StaticObjects.NeverAccessed)
                {
                    sessionFlag = (byte)(sessionFlag | SESSION_STATIC_ITEMS);
                }
                writer.Write(sessionFlag);

                if ((byte)(sessionFlag & SESSION_ITEMS) == SESSION_ITEMS)
                {
                    ((SessionStateItemCollection)sessionData.Items).Serialize(writer);
                }
                if ((byte)(sessionFlag & SESSION_STATIC_ITEMS) == SESSION_STATIC_ITEMS)
                {
                    sessionData.StaticObjects.Serialize(writer);
                }
                writer.Write(sessionData.Timeout);
            }
            finally
            {
                if (stream != null)
                {
                    buffer = stream.ToArray();
                    stream.Close();
                }
            }
            return buffer;
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(memoryStream))
                {
                    ((SessionStateItemCollection)item.Items).Serialize(binaryWriter);

                    if (newItem)
                    {
                        var query = Query.And(Query.EQ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath), Query.EQ("id", id));
                        this.mongoCollection.Remove(query);

                        var bsonDocument = new BsonDocument
                        {
                            { "applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath },
                            { "created", DateTime.Now },
                            { "expires", DateTime.Now.AddMinutes(item.Timeout) },
                            { "id", id },
                            { "lockDate", DateTime.Now },
                            { "locked", false },
                            { "lockId", 0 },
                            { "sessionStateActions", SessionStateActions.None },
                            { "sessionStateItems", memoryStream.ToArray() },
                            { "sessionStateItemsCount", item.Items.Count },
                            { "timeout", item.Timeout }
                        };

                        this.mongoCollection.Insert(bsonDocument);
                    }
                    else
                    {
                        var query = Query.And(Query.EQ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath), Query.EQ("id", id), Query.EQ("lockId", lockId.ToString()));
                        var upate = Update.Set("expires", DateTime.Now.Add(this.sessionStateSection.Timeout)).Set("items", memoryStream.ToArray()).Set("locked", false).Set("sessionStateItemsCount", item.Items.Count);
                        this.mongoCollection.Update(query, upate);
                    }
                }
            }
        }
Ejemplo n.º 26
0
 static internal void SerializeStoreData(SessionStateStoreData item, int initialStreamSize, out byte[] buf, out int length, bool compressionEnabled)
 {
     using (MemoryStream s = new MemoryStream(initialStreamSize)) {
         SessionStateUtility.Serialize(item, s);
         if (compressionEnabled)
         {
             byte[] serializedBuffer = s.GetBuffer();
             int    serializedLength = (int)s.Length;
             // truncate the MemoryStream so we can write the compressed data in it
             s.SetLength(0);
             // compress the serialized bytes
             using (DeflateStream zipStream = new DeflateStream(s, CompressionMode.Compress, true)) {
                 zipStream.Write(serializedBuffer, 0, serializedLength);
             }
             // if the session state tables have ANSI_PADDING disabled, last )s are trimmed.
             // This shouldn't happen, but to be sure, we are padding with an extra byte
             s.WriteByte((byte)0xff);
         }
         buf    = s.GetBuffer();
         length = (int)s.Length;
     }
 }
Ejemplo n.º 27
0
        public override void RemoveItem(HttpContext context,
                                        string id,
                                        object lockId,
                                        SessionStateStoreData item)
        {
            EnsureGoodId(id, true);
            string            CacheId    = CachePrefix + id;
            Cache             cache      = HttpRuntime.InternalCache;
            InProcSessionItem inProcItem = cache [CacheId] as InProcSessionItem;

            if (inProcItem == null || lockId == null || lockId.GetType() != typeof(Int32) || inProcItem.lockId != (Int32)lockId)
            {
                return;
            }

            bool locked = false;
            ReaderWriterLockSlim itemLock = null;

            try {
                itemLock = inProcItem.rwlock;
                if (itemLock != null && itemLock.TryEnterWriteLock(lockAcquireTimeout))
                {
                    locked = true;
                }
                else
                {
                    throw new ApplicationException("Failed to acquire lock after");
                }
                cache.Remove(CacheId);
            } catch {
                throw;
            } finally {
                if (locked)
                {
                    itemLock.ExitWriteLock();
                }
            }
        }
 public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
 {
     if (id == null)
     {
         throw new ArgumentNullException("id");
     }
     if (id.Length > SessionIDManager.SessionIDMaxLength)
     {
         throw new ArgumentException(ProviderResources.Session_id_too_long);
     }
     id = AppendAppIdHash(id);
     using (SessionContext context2 = ModelHelper.CreateSessionContext(this.ConnectionString))
     {
         if (context2.Sessions.Find(new object[] { id }) == null)
         {
             Session session = NewSession(id, timeout);
             SessionStateStoreData item = new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), session.Timeout);
             SaveItemToSession(session, item, this.CompressionEnabled);
             context2.Sessions.Add(session);
             context2.SaveChanges();
         }
     }
 }
Ejemplo n.º 29
0
        internal void RaiseSessionOnEnd(String id, SessionStateStoreData item) {
            HttpSessionStateContainer sessionStateContainer = new HttpSessionStateContainer(
                    id,
                    item.Items,
                    item.StaticObjects,
                    item.Timeout,
                    false,
                    SessionStateModule.s_configCookieless,
                    SessionStateModule.s_configMode,
                    true);

            HttpSessionState    sessionState = new HttpSessionState(sessionStateContainer);

            if (HttpRuntime.ShutdownInProgress) {
                // call directly when shutting down
                RaiseOnEnd(sessionState);
            }
            else {
                // post via thread pool
                SessionOnEndTargetWorkItem workItem = new SessionOnEndTargetWorkItem(this, sessionState);
                WorkItem.PostInternal(new WorkItemCallback(workItem.RaiseOnEndCallback));
            }
        }
        public void NewItemCallsSessionStore()
        {
            // Arrange & Act
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            subject.Initialize("", keyPairs, MockDocumentStore.Object);

            SessionStateStoreData sessionData = new SessionStateStoreData(
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                20
                );

            subject.SetAndReleaseItemExclusive(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), "A sessionId", sessionData, new object(), true);

            MockDocumentSession.Setup(cmd => cmd.Store(It.IsAny<SessionStateDocument>())).Verifiable();

            // Assert
            MockDocumentSession.Verify(cmd => cmd.Store(It.IsAny<SessionStateDocument>()), Times.Once());
        }
Ejemplo n.º 31
0
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        string id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            EnsureGoodId(id, true);
            byte[]       collection_data = null;
            byte[]       sobjs_data      = null;
            MemoryStream stream          = null;
            BinaryWriter writer          = null;

            try {
                SessionStateItemCollection items = item.Items as SessionStateItemCollection;
                if (items != null && items.Count > 0)
                {
                    stream = new MemoryStream();
                    writer = new BinaryWriter(stream);
                    items.Serialize(writer);
                    collection_data = stream.GetBuffer();
                }
                HttpStaticObjectsCollection sobjs = item.StaticObjects;
                if (sobjs != null && sobjs.Count > 0)
                {
                    sobjs_data = sobjs.ToByteArray();
                }
            } catch (Exception ex) {
                throw new HttpException("Failed to store session data.", ex);
            } finally {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            stateServer.SetAndReleaseItemExclusive(id, collection_data, sobjs_data, lockId, item.Timeout, newItem);
        }
 private void ResetPerRequestFields()
 {
     this._rqSessionState                 = null;
     this._rqId                           = null;
     this._rqSessionItems                 = null;
     this._rqStaticObjects                = null;
     this._rqIsNewSession                 = false;
     this._rqSessionStateNotFound         = true;
     this._rqReadonly                     = false;
     this._rqItem                         = null;
     this._rqContext                      = null;
     this._rqAr                           = null;
     this._rqLockId                       = null;
     this._rqInCallback                   = 0;
     this._rqLastPollCompleted            = DateTime.MinValue;
     this._rqExecutionTimeout             = TimeSpan.Zero;
     this._rqAddedCookie                  = false;
     this._rqIdNew                        = false;
     this._rqActionFlags                  = SessionStateActions.None;
     this._rqIctx                         = null;
     this._rqChangeImpersonationRefCount  = 0;
     this._rqTimerThreadImpersonationIctx = null;
     this._rqSupportSessionIdReissue      = false;
 }
Ejemplo n.º 33
0
        void OnAcquireRequestState(object o, EventArgs args)
        {
            Trace.WriteLine("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode().ToString("x") + ")");
            HttpApplication application = (HttpApplication)o;
            HttpContext     context     = application.Context;

            if (!(context.Handler is IRequiresSessionState))
            {
                Trace.WriteLine("Handler (" + context.Handler + ") does not require session state");
                return;
            }
            bool isReadOnly = (context.Handler is IReadOnlySessionState);

            bool supportSessionIDReissue;

            if (idManager.InitializeRequest(context, false, out supportSessionIDReissue))
            {
                return;                 // Redirected, will come back here in a while
            }
            string sessionId = idManager.GetSessionID(context);

            handler.InitializeRequest(context);

            storeData = GetStoreData(context, sessionId, isReadOnly);

            storeIsNew = false;
            if (storeData == null && !storeLocked)
            {
                storeIsNew = true;
                sessionId  = idManager.CreateSessionID(context);
                Trace.WriteLine("New session ID allocated: " + sessionId);
                bool redirected;
                bool cookieAdded;
                idManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);
                if (redirected)
                {
                    if (supportSessionIDReissue)
                    {
                        handler.CreateUninitializedItem(context, sessionId, (int)config.Timeout.TotalMinutes);
                    }
                    context.Response.End();
                    return;
                }
                else
                {
                    storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
                }
            }
            else if (storeData == null && storeLocked)
            {
                WaitForStoreUnlock(context, sessionId, isReadOnly);
            }
            else if (storeData != null &&
                     !storeLocked &&
                     storeSessionAction == SessionStateActions.InitializeItem &&
                     IsCookieLess(context, config))
            {
                storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
            }

            container = CreateContainer(sessionId, storeData, storeIsNew, isReadOnly);
            SessionStateUtility.AddHttpSessionStateToContext(app.Context, container);
            if (storeIsNew)
            {
                OnSessionStart();
                HttpSessionState hss = app.Session;

                if (hss != null)
                {
                    storeData.Timeout = hss.Timeout;
                }
            }

            // Whenever a container is abandoned, we temporarily disable the expire call back.
            // So in this case we are quite sure we have a brand new container, so we make sure it works again.
            supportsExpiration = handler.SetItemExpireCallback(OnSessionExpired);
        }
 public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
 {
     var query = Query.And(Query.EQ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath), Query.EQ("id", id), Query.EQ("lockId", lockId.ToString()));
     this.mongoCollection.Remove(query);
 }
Ejemplo n.º 35
0
		public override void RemoveItem (HttpContext context,
						 string id,
						 object lockId,
						 SessionStateStoreData item)
		{
			EnsureGoodId (id, true);
			stateServer.Remove (id, lockId);
		}
Ejemplo n.º 36
0
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            DbProviderFactory factory = ProviderFactory;
            DbConnection      conn    = CreateConnection(factory);
            DbCommand         cmd     = CreateCommand(factory, conn,
                                                      "DELETE FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND LockId = @LockId");

            DbParameterCollection parameters = cmd.Parameters;

            parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
            parameters.Add(CreateParameter <string> (factory, "@ApplicationName", ApplicationName, 255));
            parameters.Add(CreateParameter <int> (factory, "@LockId", (int)lockId));

            try {
                conn.Open();
                cmd.ExecuteNonQuery();
            } catch (Exception ex) {
                throw new ProviderException("Error removing item from database.", ex);
            } finally {
                conn.Close();
            }
        }
 public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
 {
     _client.Delete(ApplicationName, id);
 }
Ejemplo n.º 38
0
        internal SessionStateStoreData DoGet(HttpContext context,
                                             String id,
                                             UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess,
                                             out bool locked,
                                             out TimeSpan lockAge,
                                             out object lockId,
                                             out SessionStateActions actionFlags)
        {
            SessionStateStoreData item   = null;
            UnmanagedMemoryStream stream = null;
            int contentLength;

            UnsafeNativeMethods.SessionNDMakeRequestResults results;

            // Set default return values
            locked          = false;
            lockId          = null;
            lockAge         = TimeSpan.Zero;
            actionFlags     = 0;
            results.content = IntPtr.Zero;

            try {
                MakeRequest(UnsafeNativeMethods.StateProtocolVerb.GET,
                            id, exclusiveAccess, 0, 0, 0,
                            null, 0, s_networkTimeout, out results);

                switch (results.httpStatus)
                {
                case 200:
                    /* item found, deserialize it */
                    contentLength = results.contentLength;
                    if (contentLength > 0)
                    {
                        try {
                            unsafe {
                                stream = new UnmanagedMemoryStream((byte *)results.content, contentLength);
                            }
                            item = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
                        }
                        finally {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                        }

                        lockId      = results.lockCookie;
                        actionFlags = (SessionStateActions)results.actionFlags;
                    }

                    break;

                case 423:
                    /* state locked, return lock information */

                    if (0 <= results.lockAge)
                    {
                        if (results.lockAge < Sec.ONE_YEAR)
                        {
                            lockAge = new TimeSpan(0, 0, results.lockAge);
                        }
                        else
                        {
                            lockAge = TimeSpan.Zero;
                        }
                    }
                    else
                    {
                        DateTime now = DateTime.Now;
                        if (0 < results.lockDate && results.lockDate < now.Ticks)
                        {
                            lockAge = now - new DateTime(results.lockDate);
                        }
                        else
                        {
                            lockAge = TimeSpan.Zero;
                        }
                    }

                    locked = true;
                    lockId = results.lockCookie;

                    Debug.Assert((results.actionFlags & (int)SessionStateActions.InitializeItem) == 0,
                                 "(results.actionFlags & (int)SessionStateActions.InitializeItem) == 0; uninitialized item cannot be locked");
                    break;
                }
            }
            finally {
                if (results.content != IntPtr.Zero)
                {
                    UnsafeNativeMethods.SessionNDFreeBody(new HandleRef(this, results.content));
                }
            }

            return(item);
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            string        key           = this.CreateSessionStateCacheKey(id);
            bool          flag          = true;
            CacheInternal cacheInternal = HttpRuntime.CacheInternal;
            int           newLockCookie = NewLockCookie;
            ISessionStateItemCollection sessionItems  = null;
            HttpStaticObjectsCollection staticObjects = null;

            SessionIDManager.CheckIdLength(id, true);
            if (item.Items.Count > 0)
            {
                sessionItems = item.Items;
            }
            if (!item.StaticObjects.NeverAccessed)
            {
                staticObjects = item.StaticObjects;
            }
            if (!newItem)
            {
                InProcSessionState state = (InProcSessionState)cacheInternal.Get(key);
                int lockCookie           = (int)lockId;
                if (state == null)
                {
                    return;
                }
                state._spinLock.AcquireWriterLock();
                try
                {
                    if (!state._locked || (state._lockCookie != lockCookie))
                    {
                        return;
                    }
                    if (state._timeout == item.Timeout)
                    {
                        state.Copy(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, lockCookie, state._flags);
                        flag = false;
                    }
                    else
                    {
                        state._flags     |= 2;
                        newLockCookie     = lockCookie;
                        state._lockCookie = 0;
                    }
                }
                finally
                {
                    state._spinLock.ReleaseWriterLock();
                }
            }
            if (flag)
            {
                InProcSessionState state2 = new InProcSessionState(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, newLockCookie, 0);
                try
                {
                }
                finally
                {
                    cacheInternal.UtcInsert(key, state2, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state2._timeout, 0), CacheItemPriority.NotRemovable, this._callback);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
                }
            }
        }
Ejemplo n.º 40
0
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            DbCommand             cmd;
            DbCommand             deleteCmd = null;
            string                sessItems = Serialize((SessionStateItemCollection)item.Items);
            DbProviderFactory     factory   = ProviderFactory;
            string                appName   = ApplicationName;
            DbConnection          conn      = CreateConnection(factory);
            DateTime              now       = DateTime.Now;
            DbParameterCollection parameters;

            if (newItem)
            {
                deleteCmd  = CreateCommand(factory, conn, "DELETE FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND Expires < @Expires");
                parameters = deleteCmd.Parameters;

                parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));
                parameters.Add(CreateParameter <DateTime> (factory, "@Expires", now));

                cmd        = CreateCommand(factory, conn, "INSERT INTO Sessions (SessionId, ApplicationName, Created, Expires, LockDate, LockId, Timeout, Locked, SessionItems, Flags) Values (@SessionId, @ApplicationName, @Created, @Expires, @LockDate, @LockId , @Timeout, @Locked, @SessionItems, @Flags)");
                parameters = cmd.Parameters;

                parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));
                parameters.Add(CreateParameter <DateTime> (factory, "@Created", now));
                parameters.Add(CreateParameter <DateTime> (factory, "@Expires", now.AddMinutes((double)item.Timeout)));
                parameters.Add(CreateParameter <DateTime> (factory, "@LockDate", now));
                parameters.Add(CreateParameter <int> (factory, "@LockId", 0));
                parameters.Add(CreateParameter <int> (factory, "@Timeout", item.Timeout));
                parameters.Add(CreateParameter <bool> (factory, "@Locked", false));
                parameters.Add(CreateParameter <string> (factory, "@SessionItems", sessItems));
                parameters.Add(CreateParameter <int> (factory, "@Flags", 0));
            }
            else
            {
                cmd        = CreateCommand(factory, conn, "UPDATE Sessions SET Expires = @Expires, SessionItems = @SessionItems, Locked = @Locked WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND LockId = @LockId");
                parameters = cmd.Parameters;

                parameters.Add(CreateParameter <DateTime> (factory, "@Expires", now.AddMinutes((double)item.Timeout)));
                parameters.Add(CreateParameter <string> (factory, "@SessionItems", sessItems));
                parameters.Add(CreateParameter <bool> (factory, "@Locked", false));
                parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));
                parameters.Add(CreateParameter <int> (factory, "@Lockid", (int)lockId));
            }

            try
            {
                conn.Open();
                if (deleteCmd != null)
                {
                    deleteCmd.ExecuteNonQuery();
                }

                cmd.ExecuteNonQuery();
            } catch (Exception ex) {
                throw new ProviderException("Failure storing session item in database.", ex);
            } finally {
                conn.Close();
            }
        }
Ejemplo n.º 41
0
        internal unsafe SessionStateStoreData DoGet(HttpContext context, string id, System.Web.UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
        {
            SessionStateStoreData data   = null;
            UnmanagedMemoryStream stream = null;

            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            locked          = false;
            lockId          = null;
            lockAge         = TimeSpan.Zero;
            actionFlags     = SessionStateActions.None;
            results.content = IntPtr.Zero;
            try
            {
                this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.GET, id, exclusiveAccess, 0, 0, 0, null, 0, s_networkTimeout, out results);
                int httpStatus = results.httpStatus;
                if (httpStatus != 200)
                {
                    if (httpStatus != 0x1a7)
                    {
                        return(data);
                    }
                }
                else
                {
                    int contentLength = results.contentLength;
                    if (contentLength > 0)
                    {
                        try
                        {
                            stream = new UnmanagedMemoryStream((byte *)results.content, (long)contentLength);
                            data   = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
                        }
                        finally
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                        }
                        lockId      = results.lockCookie;
                        actionFlags = (SessionStateActions)results.actionFlags;
                    }
                    return(data);
                }
                if (0 <= results.lockAge)
                {
                    if (results.lockAge < 0x1e13380)
                    {
                        lockAge = new TimeSpan(0, 0, results.lockAge);
                    }
                    else
                    {
                        lockAge = TimeSpan.Zero;
                    }
                }
                else
                {
                    DateTime now = DateTime.Now;
                    if ((0L < results.lockDate) && (results.lockDate < now.Ticks))
                    {
                        lockAge = (TimeSpan)(now - new DateTime(results.lockDate));
                    }
                    else
                    {
                        lockAge = TimeSpan.Zero;
                    }
                }
                locked = true;
                lockId = results.lockCookie;
            }
            finally
            {
                if (results.content != IntPtr.Zero)
                {
                    System.Web.UnsafeNativeMethods.SessionNDFreeBody(new HandleRef(this, results.content));
                }
            }
            return(data);
        }
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        String id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            string        key                         = CreateSessionStateCacheKey(id);
            bool          doInsert                    = true;
            CacheInternal cacheInternal               = HttpRuntime.CacheInternal;
            int           lockCookieForInsert         = NewLockCookie;
            ISessionStateItemCollection items         = null;
            HttpStaticObjectsCollection staticObjects = null;

            Debug.Assert(item.Items != null, "item.Items != null");
            Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
            Debug.Assert(item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            if (item.Items.Count > 0)
            {
                items = item.Items;
            }

            if (!item.StaticObjects.NeverAccessed)
            {
                staticObjects = item.StaticObjects;
            }

            if (!newItem)
            {
                Debug.Assert(lockId != null, "lockId != null");
                InProcSessionState stateCurrent = (InProcSessionState)cacheInternal.Get(key);
                int lockCookie = (int)lockId;

                /* If the state isn't there, we probably took too long to run. */
                if (stateCurrent == null)
                {
                    return;
                }

                Debug.Trace("SessionStateClientSet", "state is inStorage; key = " + key);
                Debug.Assert((stateCurrent._flags & (int)SessionStateItemFlags.Uninitialized) == 0, "Should never set an unitialized item; key = " + key);

                stateCurrent._spinLock.AcquireWriterLock();

                try {
                    /* Only set the state if we are the owner */
                    if (!stateCurrent._locked || stateCurrent._lockCookie != lockCookie)
                    {
                        Debug.Trace("SessionStateClientSet", "Leave because we're not the owner; key = " + key);
                        return;
                    }

                    /* We can change the state in place if the timeout hasn't changed */
                    if (stateCurrent._timeout == item.Timeout)
                    {
                        stateCurrent.Copy(
                            items,
                            staticObjects,
                            item.Timeout,
                            false,
                            DateTime.MinValue,
                            lockCookie,
                            stateCurrent._flags);

                        // Don't need to insert into the Cache because an in-place copy is good enough.
                        doInsert = false;
                        Debug.Trace("SessionStateClientSet", "Changing state inplace; key = " + key);
                    }
                    else
                    {
                        /* We are going to insert a new item to replace the current one in Cache
                         * because the expiry time has changed.
                         *
                         * Pleas note that an insert will cause the Session_End to be incorrectly raised.
                         *
                         * Please note that the item itself should not expire between now and
                         * where we do UtcInsert below because CacheInternal.Get above have just
                         * updated its expiry time.
                         */
                        stateCurrent._flags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved;

                        /* By setting _lockCookie to 0, we prevent an overwriting by ReleaseExclusive
                         * when we drop the lock.
                         * The scenario can happen if another request is polling and trying to prempt
                         * the lock we have on the item.
                         */
                        lockCookieForInsert      = lockCookie;
                        stateCurrent._lockCookie = 0;
                    }
                }
                finally {
                    stateCurrent._spinLock.ReleaseWriterLock();
                }
            }

            if (doInsert)
            {
                Debug.Trace("SessionStateClientSet", "Inserting state into Cache; key = " + key);
                InProcSessionState state = new InProcSessionState(
                    items,
                    staticObjects,
                    item.Timeout,
                    false,
                    DateTime.MinValue,
                    lockCookieForInsert,
                    0);

                try {
                }
                finally {
                    // protected from ThreadAbortEx
                    cacheInternal.UtcInsert(
                        key, state, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state._timeout, 0),
                        CacheItemPriority.NotRemovable, _callback);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);

                    TraceSessionStats();
                }
            }
        }
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            string        key           = this.CreateSessionStateCacheKey(id);
            CacheInternal cacheInternal = HttpRuntime.CacheInternal;
            int           num           = (int)lockId;

            SessionIDManager.CheckIdLength(id, true);
            InProcSessionState state = (InProcSessionState)cacheInternal.Get(key);

            if (state != null)
            {
                state._spinLock.AcquireWriterLock();
                try
                {
                    if (!state._locked || (state._lockCookie != num))
                    {
                        return;
                    }
                    state._lockCookie = 0;
                }
                finally
                {
                    state._spinLock.ReleaseWriterLock();
                }
                cacheInternal.Remove(key);
            }
        }
Ejemplo n.º 44
0
 void OnSessionExpired(string id, SessionStateStoreData item)
 {
     SessionStateUtility.RaiseSessionEnd(
         CreateContainer(id, item, false, true),
         this, EventArgs.Empty);
 }
 private static string Serialize(SessionStateStoreData sessionStateItems)
 {
     return JsonConvert.SerializeObject(sessionStateItems);
 }
 public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
 {
     RedisBase.Item_Remove(id);
 }
        /// <summary>
        /// Removes the session record for DynamoDB.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="sessionId"></param>
        /// <param name="lockId"></param>
        /// <param name="item"></param>
        public override void RemoveItem(HttpContext context, string sessionId, object lockId, SessionStateStoreData item)
        {
            LogInfo("RemoveItem", sessionId, lockId, context);

            if (lockId == null)
            {
                deleteItem(sessionId);
            }
            else
            {
                Document doc = this._table.GetItem(GetHashKey(sessionId), CONSISTENT_READ_GET);
                if (doc.Contains(ATTRIBUTE_LOCK_ID))
                {
                    string currentLockId = (string)doc[ATTRIBUTE_LOCK_ID];
                    if (string.Equals(currentLockId, lockId))
                    {
                        deleteItem(sessionId);
                    }
                }
            }
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            if (newItem)
            {
                var riakSessionItem = new RiakSessionItem
                                          {
                                              SessionStoreItems = Serialize(item)
                                          };
                _client.Put(riakSessionItem.ToRiakObject());
            }
            else
            {
                var result = _client.Get(ApplicationName, id);
                var riakSessionItem = new RiakSessionItem();

                if (result.ResultCode != ResultCode.NotFound)
                {
                    riakSessionItem = new RiakSessionItem(result.Value) {Flags = 0};
                    riakSessionItem.Unlock();
                }
                else
                {
                    riakSessionItem.SessionId = id;
                    riakSessionItem.SessionContainer = ApplicationName;
                }

                riakSessionItem.Created = DateTime.Now;
                riakSessionItem.Timeout = item.Timeout;
                riakSessionItem.SessionStoreItems = Serialize(item);

                _client.Async.Put(riakSessionItem.ToRiakObject(), results => { return; });
            }
        }
Ejemplo n.º 49
0
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            int lockCookie = (int)lockId;

            this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.DELETE, id, System.Web.UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, 0, lockCookie, null, 0, s_networkTimeout, out results);
        }
Ejemplo n.º 50
0
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        string id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            if (item == null)
            {
                return;
            }

            EnsureGoodId(id, true);
            byte[]       collection_data = null;
            byte[]       sobjs_data      = null;
            MemoryStream stream          = null;
            BinaryWriter writer          = null;
            Stream       output          = null;
            GZipStream   gzip            = null;

            try {
                SessionStateItemCollection items = item.Items as SessionStateItemCollection;
                if (items != null && items.Count > 0)
                {
                    stream = new MemoryStream();
                    if (config.CompressionEnabled)
                    {
                        output = gzip = new GZipStream(stream, CompressionMode.Compress, true);
                    }
                    else
                    {
                        output = stream;
                    }
                    writer = new BinaryWriter(output);
                    items.Serialize(writer);
                    if (gzip != null)
                    {
                        gzip.Close();
                    }
                    writer.Close();
                    collection_data = stream.ToArray();
                }
                HttpStaticObjectsCollection sobjs = item.StaticObjects;
                if (sobjs != null && sobjs.Count > 0)
                {
                    sobjs_data = sobjs.ToByteArray();
                }
            } catch (Exception ex) {
                throw new HttpException("Failed to store session data.", ex);
            } finally {
                if (writer != null)
                {
                    writer.Dispose();
                }
                if (gzip != null)
                {
                    gzip.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            stateServer.SetAndReleaseItemExclusive(id, collection_data, sobjs_data, lockId, item.Timeout, newItem);
        }
 public abstract void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item);
        /// <summary>
        /// Updates the session-item information in the session-state data store with values from the current request, and clears the lock on the data.
        /// </summary>
        /// <param name="context">The HttpContext for the current request.</param>
        /// <param name="sessionId">The session identifier for the current request.</param>
        /// <param name="item">The SessionStateStoreData object that contains the current session values to be stored.</param>
        /// <param name="lockId">The lock identifier for the current request.</param>
        /// <param name="newItem">true to identify the session item as a new item; false to identify the session item as an existing item.</param>
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                         string sessionId,
                                                         SessionStateStoreData item,
                                                         object lockId,
                                                         bool newItem)
        {
            LogInfo("SetAndReleaseItemExclusive", sessionId, lockId, newItem, context);

            string serialized = serialize(item.Items as SessionStateItemCollection);

            Document newValues = new Document();
            newValues[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId);
            newValues[ATTRIBUTE_LOCKED] = false;
            newValues[ATTRIBUTE_LOCK_ID] = null;
            newValues[ATTRIBUTE_LOCK_DATE] = DateTime.Now;
            newValues[ATTRIBUTE_EXPIRES] = DateTime.Now.Add(this._timeout);
            newValues[ATTRIBUTE_FLAGS] = 0;
            newValues[ATTRIBUTE_SESSION_ITEMS] = serialized;
            newValues[ATTRIBUTE_RECORD_FORMAT_VERSION] = CURRENT_RECORD_FORMAT_VERSION;

            if (newItem)
            {
                newValues[ATTRIBUTE_CREATE_DATE] = DateTime.Now;
                this._table.PutItem(newValues);
            }
            else
            {
                Document expected = new Document();
                expected[ATTRIBUTE_LOCK_ID] = lockId.ToString();

                // Not really any reason the condition should fail unless we get in some sort of weird
                // app pool reset mode.
                try
                {
                    this._table.UpdateItem(newValues, new UpdateItemOperationConfig() { Expected = expected });
                }
                catch (ConditionalCheckFailedException) { LogInfo("(SetAndReleaseItemExclusive) Conditional check failed for update.", sessionId, context); }
            }
        }
 public abstract void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem);
Ejemplo n.º 54
0
		public override void SetAndReleaseItemExclusive (HttpContext context,
								 string id,
								 SessionStateStoreData item,
								 object lockId,
								 bool newItem)
		{
			EnsureGoodId (id, true);
			byte[] collection_data = null;
			byte[] sobjs_data = null;
			MemoryStream stream = null;
			BinaryWriter writer = null;
			Stream output = null;
#if NET_4_0
			GZipStream gzip = null;
#endif
			
			try {
				SessionStateItemCollection items = item.Items as SessionStateItemCollection;
				if (items != null && items.Count > 0) {
					stream = new MemoryStream ();
#if NET_4_0
					if (config.CompressionEnabled)
						output = gzip = new GZipStream (stream, CompressionMode.Compress, true);
					else
#endif
						output = stream;
					writer = new BinaryWriter (output);
					items.Serialize (writer);
#if NET_4_0
					if (gzip != null)
						gzip.Close ();
#endif
					writer.Close ();
					collection_data = stream.ToArray ();
				}
				HttpStaticObjectsCollection sobjs = item.StaticObjects;
				if (sobjs != null && sobjs.Count > 0)
					sobjs_data = sobjs.ToByteArray ();
			} catch (Exception ex) {
				throw new HttpException ("Failed to store session data.", ex);
			} finally {

#if NET_4_0
				if (writer != null)
					writer.Dispose ();
				if (gzip != null)
					gzip.Dispose ();
#else
				if (writer != null)
					((IDisposable)writer).Dispose ();
#endif
				if (stream != null)
					stream.Dispose ();
			}
			
			stateServer.SetAndReleaseItemExclusive (id, collection_data, sobjs_data, lockId, item.Timeout, newItem);
		}
Ejemplo n.º 55
0
        /* In certain situations the 'item' parameter passed to SetAndReleaseItemExclusive
         * may be null. The issue was reported in bug #333898, but the reporter cannot
         * provide a test case that triggers the issue. Added work around the problem
         * in the way that should have the least impact on the rest of the code. If 'item'
         * is null, then the new session item is created without the items and staticItems
         * collections - they will be initialized to defaults when retrieving the session
         * item. This is not a correct fix, but since there is no test case this is the best
         * what can be done right now.
         */
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        string id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            EnsureGoodId(id, true);
            string                      CacheId    = CachePrefix + id;
            Cache                       cache      = HttpRuntime.InternalCache;
            InProcSessionItem           inProcItem = cache [CacheId] as InProcSessionItem;
            ISessionStateItemCollection itemItems  = null;
            int itemTimeout = 20;
            HttpStaticObjectsCollection itemStaticItems = null;

            if (item != null)
            {
                itemItems       = item.Items;
                itemTimeout     = item.Timeout;
                itemStaticItems = item.StaticObjects;
            }

            if (newItem || inProcItem == null)
            {
                inProcItem           = new InProcSessionItem();
                inProcItem.timeout   = itemTimeout;
                inProcItem.expiresAt = DateTime.UtcNow.AddMinutes(itemTimeout);
                if (lockId.GetType() == typeof(Int32))
                {
                    inProcItem.lockId = (Int32)lockId;
                }
            }
            else
            {
                if (lockId == null || lockId.GetType() != typeof(Int32) || inProcItem.lockId != (Int32)lockId)
                {
                    return;
                }
                inProcItem.resettingTimeout = true;
                cache.Remove(CacheId);
            }

            bool locked = false;
            ReaderWriterLockSlim itemLock = null;

            try {
                itemLock = inProcItem.rwlock;
                if (itemLock != null && itemLock.TryEnterWriteLock(lockAcquireTimeout))
                {
                    locked = true;
                }
                else
                {
                    throw new ApplicationException("Failed to acquire lock");
                }
                if (inProcItem.resettingTimeout)
                {
                    UpdateSessionItemTimeout(itemTimeout, CacheId);
                }
                else
                {
                    inProcItem.locked      = false;
                    inProcItem.items       = itemItems;
                    inProcItem.staticItems = itemStaticItems;
                    InsertSessionItem(inProcItem, itemTimeout, CacheId);
                }
            } catch {
                throw;
            } finally {
                if (locked && itemLock != null)
                {
                    itemLock.ExitWriteLock();
                }
            }
        }
Ejemplo n.º 56
0
        private SessionStateStoreData GetSessionStoreItem(bool lockRecord, HttpContext context, string id, out bool locked,
                                                          out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
        {
            SessionStateStoreData item = null;

            lockAge     = TimeSpan.Zero;
            lockId      = null;
            locked      = false;
            actionFlags = 0;

            DbProviderFactory     factory = ProviderFactory;
            DbConnection          conn    = CreateConnection(factory);
            string                appName = ApplicationName;
            DbCommand             cmd     = null;
            DbDataReader          reader  = null;
            DbParameterCollection parameters;
            DateTime              expires;
            string                serializedItems = String.Empty;
            bool     foundRecord = false;
            bool     deleteData  = false;
            int      timeout     = 0;
            DateTime now         = DateTime.Now;

            try {
                conn.Open();
                if (lockRecord)
                {
                    cmd        = CreateCommand(factory, conn, "UPDATE Sessions SET Locked = @Locked, LockDate = @LockDate WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND Expires > @Expires");
                    parameters = cmd.Parameters;

                    parameters.Add(CreateParameter <bool> (factory, "@Locked", true));
                    parameters.Add(CreateParameter <DateTime> (factory, "@LockDate", now));
                    parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                    parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));
                    parameters.Add(CreateParameter <DateTime> (factory, "@Expires", now));

                    if (cmd.ExecuteNonQuery() == 0)
                    {
                        locked = true;
                    }
                    else
                    {
                        locked = false;
                    }
                }

                cmd        = CreateCommand(factory, conn, "SELECT Expires, SessionItems, LockId, LockDate, Flags, Timeout FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
                parameters = cmd.Parameters;

                parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));

                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                while (reader.Read())
                {
                    expires = reader.GetDateTime(reader.GetOrdinal("Expires"));

                    if (expires < now)
                    {
                        locked     = false;
                        deleteData = true;
                    }
                    else
                    {
                        foundRecord = true;
                    }

                    serializedItems = reader.GetString(reader.GetOrdinal("SessionItems"));
                    lockId          = reader.GetInt32(reader.GetOrdinal("LockId"));
                    lockAge         = now.Subtract(reader.GetDateTime(reader.GetOrdinal("LockDate")));
                    actionFlags     = (SessionStateActions)reader.GetInt32(reader.GetOrdinal("Flags"));
                    timeout         = reader.GetInt32(reader.GetOrdinal("Timeout"));
                }
                reader.Close();

                if (deleteData)
                {
                    cmd        = CreateCommand(factory, conn, "DELETE FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
                    parameters = cmd.Parameters;

                    parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                    parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));

                    cmd.ExecuteNonQuery();
                }

                if (!foundRecord)
                {
                    locked = false;
                }

                if (foundRecord && !locked)
                {
                    lockId = (int)lockId + 1;

                    cmd        = CreateCommand(factory, conn, "UPDATE Sessions SET LockId = @LockId, Flags = 0 WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
                    parameters = cmd.Parameters;

                    parameters.Add(CreateParameter <int> (factory, "@LockId", (int)lockId));
                    parameters.Add(CreateParameter <string> (factory, "@SessionId", id, 80));
                    parameters.Add(CreateParameter <string> (factory, "@ApplicationName", appName, 255));

                    cmd.ExecuteNonQuery();

                    if (actionFlags == SessionStateActions.InitializeItem)
                    {
                        item = CreateNewStoreData(context, (int)sessionConfig.Timeout.TotalMinutes);
                    }
                    else
                    {
                        item = Deserialize(context, serializedItems, timeout);
                    }
                }
            } catch (Exception ex) {
                throw new ProviderException("Unable to retrieve session item from database.", ex);
            } finally {
                if (reader != null)
                {
                    reader.Close();
                }

                conn.Close();
            }

            return(item);
        }
Ejemplo n.º 57
0
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buffer;
            int    num;
            int    num2;

            try
            {
                SessionStateUtility.SerializeStoreData(item, 0, out buffer, out num, s_configCompressionEnabled);
            }
            catch
            {
                if (!newItem)
                {
                    this.ReleaseItemExclusive(context, id, lockId);
                }
                throw;
            }
            if (lockId == null)
            {
                num2 = 0;
            }
            else
            {
                num2 = (int)lockId;
            }
            this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.PUT, id, System.Web.UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, item.Timeout, num2, buffer, num, s_networkTimeout, out results);
        }