public SessionStateStoreData ToStoreData(HttpContext context)
        {
            // Get static objects
            var sObjects = SessionStateUtility.GetSessionStaticObjects(context);

            return(new SessionStateStoreData(Items, sObjects, Timeout));
        }
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     _log.Trace("CreateNewStoreData called.");
     return(new SessionStateStoreData(new SessionStateItemCollection(),
                                      SessionStateUtility.GetSessionStaticObjects(context),
                                      timeout));
 }
Exemple #3
0
            private static SessionStateStoreData Deserialize(
                HttpContext context,
                Stream stream)
            {
                int timeout;
                SessionStateItemCollection  stateItemCollection;
                HttpStaticObjectsCollection staticObjects;

                try
                {
                    BinaryReader reader = new BinaryReader(stream);
                    timeout = reader.ReadInt32();
                    bool flag = reader.ReadBoolean();
                    int  num  = reader.ReadBoolean() ? 1 : 0;
                    stateItemCollection = !flag ? new SessionStateItemCollection() : SessionStateItemCollection.Deserialize(reader);
                    staticObjects       = num == 0 ? SessionStateUtility.GetSessionStaticObjects(context) : HttpStaticObjectsCollection.Deserialize(reader);
                    if (reader.ReadByte() != byte.MaxValue)
                    {
                        throw new ProviderException(MsgManager.GetMsg(ErrRes.INVALID_SESSION_STATE));
                    }
                }
                catch (EndOfStreamException ex)
                {
                    throw new ProviderException(MsgManager.GetMsg(ErrRes.INVALID_SESSION_STATE));
                }
                return(new SessionStateStoreData((ISessionStateItemCollection)stateItemCollection, staticObjects, timeout));
            }
Exemple #4
0
        //
        // GetSessionStoreItem is called by both the GetItem and
        // GetItemExclusive methods. GetSessionStoreItem retrieves the
        // session data from the data source. If the lockRecord parameter
        // is true (in the case of GetItemExclusive), then GetSessionStoreItem
        // locks the record and sets a new LockId and LockDate.
        //
        private SessionStateStoreData GetSessionStoreItem(HttpContext context,
                                                          string sessionID,
                                                          out bool locked,
                                                          out TimeSpan lockAge,
                                                          out object lockId,
                                                          out SessionStateActions actionFlags)
        {
            // Initial values for return value and out parameters.
            lockAge     = TimeSpan.Zero;
            lockId      = null;
            locked      = false;
            actionFlags = 0;

            lock (_sessionItemsBySessionIdDict)
            {
                if (_sessionItemsBySessionIdDict.ContainsKey(sessionID))
                {
                    var sessionWithTimeout = _sessionItemsBySessionIdDict[sessionID];
                    if (sessionWithTimeout.ExpiryDateTime < DateTime.Now)
                    {
                        _sessionItemsBySessionIdDict.Remove(sessionID);
                    }
                    else
                    {
                        return(new SessionStateStoreData(sessionWithTimeout.Session, SessionStateUtility.GetSessionStaticObjects(context), _timeout));
                    }
                }
            }

            return(null);
        }
Exemple #5
0
        public void MyTestInitialize()
        {
            var request = new SimpleWorkerRequest("/dummy", @"c:\inetpub\wwwroot\dummy", "dummy.html", null, new StringWriter());

            HttpContext.Current = new HttpContext(request);
            SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, new HttpSessionState2());
        }
        public HttpContext InitializeHttpContext()
        {
            var testContext = new HttpContext(
                new HttpRequest("", "http://dotnet.try0.jp", ""),
                new HttpResponse(new StringWriter())
                );


            var sessionStateContainer = new HttpSessionStateContainer(
                "",
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                20000,
                true,
                HttpCookieMode.UseCookies,
                SessionStateMode.InProc,
                false
                );

            SessionStateUtility.AddHttpSessionStateToContext(testContext, sessionStateContainer);

            HttpContext.Current = testContext;

            FeedbackMessageStore.Initialize(FeedbackMessageStoreHolder.Instance);
            return(testContext);
        }
        //</Snippet4>


        //<Snippet5>
        //
        // Event handler for HttpApplication.ReleaseRequestState
        //

        private void OnReleaseRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;
            string          sessionID;

            // Read the session state from the context
            HttpSessionStateContainer stateProvider =
                (HttpSessionStateContainer)(SessionStateUtility.GetHttpSessionStateFromContext(context));

            // If Session.Abandon() was called, remove the session data from the local Hashtable
            // and execute the Session_OnEnd event from the Global.asax file.
            if (stateProvider.IsAbandoned)
            {
                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                    sessionID = pSessionIDManager.GetSessionID(context);
                    pSessionItems.Remove(sessionID);
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }

                SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(context);
        }
 public void RaiseOnEnd(HttpSessionStateContainer sessionStateContainer)
 {
     if (_sessionEndEventHandlerCount > 0)
     {
         SessionStateUtility.RaiseSessionEnd(sessionStateContainer, this, EventArgs.Empty);
     }
 }
        private void InitStateStoreItem(bool addToContext)
        {
            Debug.Assert(_rqId != null, "_rqId != null");

            if (_rqItem == null)
            {
                _rqItem = _store.CreateNewStoreData(_rqContext, s_timeout);
            }

            _rqSessionItems = _rqItem.Items;
            if (_rqSessionItems == null)
            {
                throw new HttpException(string.Format(SR.Null_value_for_SessionStateItemCollection));
            }

            // No check for null because we allow our custom provider to return a null StaticObjects.
            _rqStaticObjects = _rqItem.StaticObjects;

            _rqSessionItems.Dirty = false;

            _rqSessionState = new HttpSessionStateContainer(
                _rqId,
                _rqSessionItems,
                _rqStaticObjects,
                _rqItem.Timeout,
                _rqIsNewSession,
                ConfigCookieless,
                s_configMode,
                _rqReadonly);

            if (addToContext)
            {
                SessionStateUtility.AddHttpSessionStateToContext(_rqContext.ApplicationInstance.Context, _rqSessionState);
            }
        }
Exemple #10
0
        /// <summary>Sets the HTTP context with a valid simulated request.</summary>
        /// <param name="host">The host that must be associated with the session. Normally 'localhost' will suffice.</param>
        /// <param name="application">The name of the application that requires the session. Any name will do.</param>
        /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="application"/> is <see langword="null"/> or empty.</exception>
        public static void SetHttpContextWithSimulatedRequest(string host, string application)
        {
            Guard.ArgumentIsNotNullOrEmpty(host, nameof(host), "Specify a valid host");
            Guard.ArgumentIsNotNullOrEmpty(application, nameof(application), "Specify a valid application");

            if (HttpContext.Current != null)
            {
                HttpContext.Current.Session.Clear();
            }
            else
            {
                /* These values are purely to satisfy the constructors of the HttpContext related objects. They don't have to represent a real-life
                 * web-application.*/
                string     appVirtualDir  = "/";
                string     appPhysicalDir = @"d:\projects\Web\";
                string     page           = application.Replace("/", string.Empty) + "/default.aspx";
                string     query          = string.Empty;
                TextWriter output         = null;

                SimulatedHttpRequest workerRequest = new SimulatedHttpRequest(appVirtualDir, appPhysicalDir, page, query, output, host);
                HttpContext.Current = new HttpContext(workerRequest);
                HttpSessionStateContainer session = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(),
                                                                                  SessionStateUtility.GetSessionStaticObjects(HttpContext.Current), 30, true, HttpCookieMode.AutoDetect, SessionStateMode.Custom, false);

                SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, session);
            }
        }
        private void OnReleaseRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;

            if (context == null || context.Session == null)
            {
                return;
            }

            releaseCalled = true;

            // Read the session state from the context
            var stateContainer =
                (TaskWaitRedisHttpSessionStateContainer)SessionStateUtility.GetHttpSessionStateFromContext(context);

            // If Session.Abandon() was called, remove the session data from the local Hashtable
            // and execute the Session_OnEnd event from the Global.asax file.
            if (stateContainer.IsAbandoned)
            {
                stateContainer.Clear();
                SessionStateUtility.RaiseSessionEnd(stateContainer, this, EventArgs.Empty);
            }
            else
            {
                stateContainer.WaitOnAllPersistent();
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(context);
        }
 /// <summary>
 /// Creates a new, empty Session for first-time requests
 /// </summary>
 /// <param name="context">The HttpContext containing the current web request</param>
 /// <param name="timeout">The timeout of the Session to be created</param>
 /// <returns>A SessionStateStoreData object containing Session keys and properties</returns>
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     return(new SessionStateStoreData(
                new RedisSessionStateItemCollection(),
                SessionStateUtility.GetSessionStaticObjects(context),
                timeout));
 }
        //
        // Recursivly remove expired session data from session collection.
        //
        private void RemoveExpiredSessionData()
        {
            string sessionID;

            foreach (DictionaryEntry entry in pSessionItems)
            {
                SessionItem item = (SessionItem)entry.Value;

                if (DateTime.Compare(item.Expires, DateTime.Now) <= 0)
                {
                    sessionID = entry.Key.ToString();
                    pSessionItems.Remove(entry.Key);

                    HttpSessionStateContainer stateProvider =
                        new HttpSessionStateContainer(sessionID,
                                                      item.Items,
                                                      item.StaticObjects,
                                                      pTimeout,
                                                      false,
                                                      pCookieMode,
                                                      SessionStateMode.Custom,
                                                      false);

                    SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
                    this.RemoveExpiredSessionData();
                    break;
                }
            }
        }
Exemple #14
0
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     Debug.Assert(context != null);
     return(new SessionStateStoreData(new SessionStateItemCollection(),
                                      SessionStateUtility.GetSessionStaticObjects(context),
                                      timeout));
 }
Exemple #15
0
 private SessionStateStoreData WrapData(NoLockingStoredData sessionValue, HttpContext context, int timeout)
 {
     return(new SessionStateStoreData(
                sessionValue?.GetSessionData() ?? new NoLockingSessionData(),
                context != null ? SessionStateUtility.GetSessionStaticObjects(context) : null,
                timeout));
 }
Exemple #16
0
        public void sessionDestroyed(HttpSessionEvent se)
        {
            bool setDomain = [email protected]() == null;

            if (setDomain)
            {
                AppDomain servletDomain = (AppDomain)se.getSession().getServletContext().getAttribute(J2EEConsts.APP_DOMAIN);
                if (servletDomain == null)
                {
                    return;
                }
                [email protected](servletDomain);
            }
            try {
                HttpSessionStateContainer container =
                    ServletSessionStateStoreProvider.CreateContainer(se.getSession());

                SessionStateUtility.RaiseSessionEnd(container, this, EventArgs.Empty);
            }
            catch (Exception e) {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
            finally {
                if (setDomain)
                {
                    [email protected]();
                }
            }
        }
        // Release session state
        private Task ReleaseStateAsync(HttpApplication application)
        {
            _releaseCalled = true;

            if (_rqSessionState == null)
            {
                return(Task.CompletedTask);
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(_rqContext.ApplicationInstance.Context);

            /*
             * Don't store untouched new sessions.
             */

            if (
                // The store doesn't have the session state.
                // ( Please note we aren't checking _rqIsNewSession because _rqIsNewSession
                // is lalso true if the item is converted from temp to perm in a GetItemXXX() call.)
                _rqSessionStateNotFound

                // OnStart is not defined
                && _sessionStartEventHandler == null

                // Nothing has been stored in session state
                && !_rqSessionItems.Dirty &&
                (_rqStaticObjects == null || _rqStaticObjects.NeverAccessed)
                )
            {
                RemoveSessionId(application.Context);
                return(Task.CompletedTask);
            }

            return(ReleaseStateAsyncImpl(application));
        }
Exemple #18
0
        public HttpContext FakeHttpContext(Dictionary <string, object> sessionVariables, string path)
        {
            var httpRequest  = new HttpRequest(string.Empty, path, string.Empty);
            var stringWriter = new StringWriter();
            var httpResponce = new HttpResponse(stringWriter);
            var httpContext  = new HttpContext(httpRequest, httpResponce);

            httpContext.User        = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
            var sessionContainer = new HttpSessionStateContainer(
                "id",
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                10,
                true,
                HttpCookieMode.AutoDetect,
                SessionStateMode.InProc,
                false);

            foreach (var var in sessionVariables)
            {
                sessionContainer.Add(var.Key, var.Value);
            }

            SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
            return(httpContext);
        }
Exemple #19
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));
        }
        /// <summary>
        /// Event handler for HttpApplication.AcquireRequestState
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        private void OnAcquireRequestState(object source, EventArgs args)
        {
            acquireCalled = true;

            HttpApplication app         = (HttpApplication)source;
            HttpContext     context     = app.Context;
            bool            isNew       = false;
            SessionItem     sessionData = null;
            bool            supportSessionIdReissue;

            sessionIdManager.InitializeRequest(context, false, out supportSessionIdReissue);
            var sessionId = sessionIdManager.GetSessionID(context);


            if (sessionId != null)
            {
                sessionData = GetSessionItem(sessionId);
            }
            else
            {
                bool redirected, cookieAdded;

                sessionId = sessionIdManager.CreateSessionID(context);
                sessionIdManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);

                if (redirected)
                {
                    return;
                }
            }

            if (sessionData == null)
            {
                // Identify the session as a new session state instance. Create a new SessionItem
                // and add it to the local Hashtable.

                isNew = true;

                sessionData = AddNewSessionItem(sessionId,
                                                SessionStateUtility.GetSessionStaticObjects(context));
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                                                             new HttpSessionStateContainer(sessionId,
                                                                                           sessionData.Items,
                                                                                           sessionData.StaticObjects,
                                                                                           Timeout,
                                                                                           isNew,
                                                                                           CookieMode,
                                                                                           SessionStateMode.Custom,
                                                                                           false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
        private void OnAcquireRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;
            bool            isNew   = false;
            string          sessionId;

            RedisSessionItemHash sessionItemCollection = null;
            bool supportSessionIDReissue = true;

            sessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
            sessionId = sessionIDManager.GetSessionID(context);

            if (sessionId == null)
            {
                bool redirected, cookieAdded;

                sessionId = sessionIDManager.CreateSessionID(context);
                sessionIDManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);

                isNew = true;

                if (redirected)
                {
                    return;
                }
            }

            if (!RequiresSessionState(new HttpContextWrapper(context)))
            {
                return;
            }

            releaseCalled = false;

            sessionItemCollection = new RedisSessionItemHash(sessionId, redisConfig.SessionTimeout, GetRedisConnection());

            if (sessionItemCollection.Count == 0)
            {
                isNew = true;
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                                                             new TaskWaitRedisHttpSessionStateContainer(sessionId,
                                                                                                        sessionItemCollection,
                                                                                                        SessionStateUtility.GetSessionStaticObjects(context),
                                                                                                        redisConfig.SessionTimeout,
                                                                                                        isNew,
                                                                                                        redisConfig.CookieMode,
                                                                                                        SessionStateMode.Custom,
                                                                                                        false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
Exemple #22
0
        private SessionStateStoreData GetSessionStateStoreData(bool exclusive, HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
        {
            actions = SessionStateActions.None;
            lockAge = TimeSpan.Zero;
            locked  = false;
            lockId  = null;

            var query        = Query.And(Query.EQ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath), Query.EQ("id", id));
            var bsonDocument = this.mongoCollection.FindOneAs <BsonDocument>(query);

            if (bsonDocument == null)
            {
                locked = false;
            }
            else if (bsonDocument["expires"].ToUniversalTime() <= DateTime.Now)
            {
                locked = false;
                this.mongoCollection.Remove(Query.And(Query.EQ("applicationVirtualPath", HostingEnvironment.ApplicationVirtualPath), Query.EQ("id", id)));
            }
            else if (bsonDocument["locked"].AsBoolean == true)
            {
                lockAge = DateTime.Now.Subtract(bsonDocument["lockDate"].ToUniversalTime());
                locked  = true;
                lockId  = bsonDocument["lockId"].AsInt32;
            }
            else
            {
                locked  = false;
                lockId  = bsonDocument["lockId"].AsInt32;
                actions = (SessionStateActions)bsonDocument["sessionStateActions"].AsInt32;
            }

            if (exclusive)
            {
                lockId  = (int)lockId + 1;
                actions = SessionStateActions.None;

                var update = Update.Set("lockDate", DateTime.Now).Set("lockId", (int)lockId).Set("locked", true).Set("sessionStateActions", SessionStateActions.None);
                this.mongoCollection.Update(query, update);
            }

            if (actions == SessionStateActions.InitializeItem)
            {
                return(this.CreateNewStoreData(context, this.sessionStateSection.Timeout.Minutes));
            }

            using (var memoryStream = new MemoryStream(bsonDocument["sessionStateItems"].AsByteArray))
            {
                var sessionStateItems = new SessionStateItemCollection();

                if (memoryStream.Length > 0)
                {
                    var binaryReader = new BinaryReader(memoryStream);
                    sessionStateItems = SessionStateItemCollection.Deserialize(binaryReader);
                }

                return(new SessionStateStoreData(sessionStateItems, SessionStateUtility.GetSessionStaticObjects(context), bsonDocument["timeout"].AsInt32));
            }
        }
        // GET: api/SessionStateApi
        public IEnumerable <string> Get()
        {
            IHttpSessionState session = SessionStateUtility.GetHttpSessionStateFromContext(HttpContext.Current);

            foreach (string key in session.Keys)
            {
                yield return(key + ":" + session[key].ToString());
            }
        }
Exemple #24
0
        /// <summary>
        /// Adds a new session-state item to the data store.
        /// </summary>
        /// <param name="context">The <see cref="T:System.Web.HttpContext" /> for the current request.</param>
        /// <param name="id">The <see cref="P:System.Web.SessionState.HttpSessionState.SessionID" />
        /// for the current request.</param>
        /// <param name="timeout">The session <see cref="P:System.Web.SessionState.HttpSessionState.Timeout" />
        /// for the current request.</param>
        public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
        {
            var cache = _expiryCacheHolder.GetCacheWithExpiry((long)timeout * 60);

            var key = GetKey(id);

            var data = new IgniteSessionStateStoreData(SessionStateUtility.GetSessionStaticObjects(context), timeout);

            PutItem(key, data, cache);
        }
Exemple #25
0
        /// <summary>
        /// Creates a new SessionStateStoreData object to be used for the current request.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
        {
            HttpStaticObjectsCollection sessionStatics = null;

            if (context != null)
            {
                sessionStatics = SessionStateUtility.GetSessionStaticObjects(context);
            }
            return(new SessionStateStoreData(new SessionStateItemCollection(), sessionStatics, timeout));
        }
        // DeSerialize is called by the GetSessionStoreItem method to
        // convert the Base64 string stored in the Access Memo field to a
        // SessionStateItemCollection.
        private SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
        {
            MemoryStream ms = new MemoryStream(Convert.FromBase64String(serializedItems));
            SessionStateItemCollection sessionItems = new SessionStateItemCollection();

            if (ms.Length > 0)
            {
                BinaryReader reader = new BinaryReader(ms);
                sessionItems = SessionStateItemCollection.Deserialize(reader);
            }
            return(new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout));
        }
        /// <summary>
        /// Создается новый объект, который будет использоваться для хранения состояния сессии в течении запроса.
        /// Мы можем установить в него некоторые предопределенные значения, которые нам понадобятся.
        /// </summary>
        public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
        {
            var data = new SessionStateStoreData(new SessionStateItemCollection(),
                                                 SessionStateUtility.GetSessionStaticObjects(context),
                                                 timeout);

            if (data.Items["UserId"] == null)
            {
                data.Items["UserId"] = 0;
            }
            return(data);
        }
        private static SessionStateStoreData Deserialize(HttpContext context,
                                                         byte[] serializedItems, int timeout)
        {
            SessionStateItemCollection items =
                serializedItems != null && serializedItems.Length > 0 ?
                SessionStateItemCollection.Deserialize(
                    new BinaryReader(new MemoryStream(serializedItems))) :
                new SessionStateItemCollection();

            return(new SessionStateStoreData(items,
                                             SessionStateUtility.GetSessionStaticObjects(context), timeout));
        }
Exemple #29
0
 internal static SessionStateStoreData CreateLegitStoreData(HttpContext context, ISessionStateItemCollection sessionItems, HttpStaticObjectsCollection staticObjects, int timeout)
 {
     if (sessionItems == null)
     {
         sessionItems = new SessionStateItemCollection();
     }
     if (staticObjects == null && context != null)
     {
         staticObjects = SessionStateUtility.GetSessionStaticObjects(context);
     }
     return(new SessionStateStoreData(sessionItems, staticObjects, timeout));
 }
Exemple #30
0
        private static SessionStateStoreData CreateLegitStoreData(HttpContext context, int timeout)
        {
            ISessionStateItemCollection sessionItems  = new SessionStateItemCollection();
            HttpStaticObjectsCollection staticObjects = null;

            if (context != null)
            {
                staticObjects = SessionStateUtility.GetSessionStaticObjects(context);
            }

            return(new SessionStateStoreData(sessionItems, staticObjects, timeout));
        }