public void ExpectedRavenDbCallsAreMade()
        {
            // Arrange
            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);
            object lockId = 0;

            string providedSessionId = "A sessionId";

            SessionStateDocument sessionObject = TestSessionDocumentFactory.CreateSessionStateDocument(providedSessionId, expectedAppName);
            sessionObject.Expiry = DateTime.UtcNow.AddDays(1);

            var sessionItems = new SessionStateItemCollection();

            sessionItems["ACar"] = new Car("A6", "Audi");

            sessionObject.SessionItems = subject.Serialize(sessionItems);

            SessionStateStoreData item = RavenSessionStateStoreProvider.Deserialize(null, sessionObject.SessionItems, 10);

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

            subject.Initialize("A name", keyPairs, MockDocumentStore.Object);

            // Act
            subject.CreateUninitializedItem(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), providedSessionId, 10);

            // Assert
            MockDocumentSession.Verify(cmd => cmd.Store(It.IsAny<SessionStateDocument>()), Times.Once());
            MockDocumentSession.Verify(cmd => cmd.SaveChanges(), Times.Once());
        }
 public FakeHttpContext(string relativeUrl, 
     IPrincipal principal, NameValueCollection formParams,
     NameValueCollection queryStringParams, HttpCookieCollection cookies,
     SessionStateItemCollection sessionItems, NameValueCollection serverVariables)
     : this(relativeUrl, null, principal, formParams, queryStringParams, cookies, sessionItems, serverVariables)
 {
 }
Ejemplo n.º 3
0
        public void TestUpdates()
        {
            SessionStateItemCollection items = new SessionStateItemCollection();
            items["Val1"] = "value";
            byte[] serializedItems = Serialize(items);
            Binary b = new Binary(serializedItems);
            List<string> ids = new List<string>();
            ICursor allSessions;
            using (var mongo = new Mongo(config))
            {
                mongo.Connect();
                allSessions = mongo["session_store"]["sessions"].FindAll();
                foreach (Document session in allSessions.Documents)
                {
                    string id = (string)session["SessionId"];
                    ids.Add(id);

                }
            }
            foreach (string s in ids)
            {
                var sessionStore = new SessionStore("test");
                sessionStore.UpdateSession(s, 2, b, "AppName", items.Count, 0);
            }
        }
        public FakeControllerContext(
            IController controller,
            string userName = null,
            string[] roles = null,
            NameValueCollection formParams = null,
            NameValueCollection queryStringParams = null,
            HttpCookieCollection cookies = null,
            SessionStateItemCollection sessionItems = null,
            NameValueCollection headers = null,
			Uri uri = null
            )
            : base(new FakeHttpContext(
                    new FakePrincipal(
                        new FakeIdentity(userName), 
                        roles), 
                    formParams, 
                    queryStringParams, 
                    cookies, 
                    sessionItems,
                    headers,
					uri), 
                new RouteData(), 
                controller as ControllerBase)
        {
        }
Ejemplo n.º 5
0
        public FakeHttpContext(
            IPrincipal principal,
            IFormParamsProvider formParams,
            IQueryStringParamsProvider queryStringParams,
            ICookieProvider cookies,
            IServerVariablesParamsProvider serverVariablesParams,
            IHeadersParamsProvider headersParams,
            SessionStateItemCollection sessionItems,
            HttpServerUtilityBase server,
            FakeHttpRequest request,
            IHttpContextBehavior contextBehavior)
        {
            User = principal;
            _sessionItems = sessionItems ?? new SessionStateItemCollection();
            _request = request ?? new FakeHttpRequest(formParams, queryStringParams, cookies, serverVariablesParams, headersParams);
            _request.SetIsAuthenticated(User.Identity != null ? User.Identity.IsAuthenticated : false);
            _server = server ?? new Mock<HttpServerUtilityBase>().Object;

            var httpResponse = new Mock<HttpResponseBase>();
            httpResponse.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s);
            _response = httpResponse.Object;

            _behavior = contextBehavior;

            _items = new Hashtable();
        }
Ejemplo n.º 6
0
		public void SessionLifetimeReturnsSameInstanceForSameSessionAndDifferentInstanceForDifferentSession()
		{
			// Arrange
			using (var container = new IocContainer())
			{
				var sessionItems1 = new SessionStateItemCollection();
				var sessionItems2 = new SessionStateItemCollection();
				var context1 = new FakeHttpContext("Http://fakeUrl1.com", null, null, null, null, sessionItems1);
				var context2 = new FakeHttpContext("Http://fakeUrl2.com", null, null, null, null, sessionItems2);

				HttpContextBase currentContext = null;

				var lifetime = new SessionLifetime(() => currentContext);		// better solution for injecting HttpContext ?

				container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime);

				// Act
				currentContext = context1;

				var result1 = container.Resolve<IFoo>();
				var result2 = container.Resolve<IFoo>();

				currentContext = context2;

				var result3 = container.Resolve<IFoo>();

				// Assert
				Assert.IsNotNull(result1);
				Assert.IsNotNull(result2);
				Assert.IsNotNull(result3);

				Assert.AreSame(result1, result2);
				Assert.AreNotSame(result1, result3);
			}
		}
        public override SessionStateStoreData GetItem(HttpContext context,
				string id,
				out bool locked,
				out TimeSpan lockAge,
				out object lockId,
				out SessionStateActions actions)
        {
            var redis = GetRedisConnection();
            var getSessionData = redis.Hashes.GetAll(0, GetKeyForSessionId(id));
            locked = false;
            lockAge = new TimeSpan(0);
            lockId = null;
            actions = SessionStateActions.None;

            if (getSessionData.Result == null) {
                return null;
            }
            else {
                var sessionItems = new SessionStateItemCollection();
                var sessionDataHash = getSessionData.Result;
                if (sessionDataHash.Count == 3) {
                    sessionItems = Deserialize(sessionDataHash["data"]);

                    var timeoutMinutes = BitConverter.ToInt32(sessionDataHash["timeoutMinutes"], 0);
                    redis.Keys.Expire(0, GetKeyForSessionId(id), timeoutMinutes * 60);
                }

                return new SessionStateStoreData(sessionItems,
                     SessionStateUtility.GetSessionStaticObjects(context),
                     redisConfig.SessionTimeout);
            }
        }
        /// <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;
            }
        }
Ejemplo n.º 9
0
        public MongoSessionDocument()
        {
            ApplicationName = "WinDemo.Mongodb";
            LockId = 0;
            Locked = false;
            Flags = 0;
            User = "******";
            Timeout = 50;
            Created = DateTime.UtcNow;
            LockDate = DateTime.UtcNow;
            Expires = Created.AddMinutes(Timeout);

            SessionStateItemCollection col = new SessionStateItemCollection();
            col["key1"] = new
            {
                ID = new Random().Next(100, 100000),
                Name = "ZY",
                Age = 11
            };
            col["key2"] = new
            {
                ID = new Random().Next(100, 100000),
                Name = "ZY",
                Age = 11
            };
            SessionItems = col;
        }
 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;
 }
Ejemplo n.º 11
0
 public FakeHttpContext(FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems )
 {
     _principal = principal;
     _formParams = formParams;
     _queryStringParams = queryStringParams;
     _cookies = cookies;
     _sessionItems = sessionItems;
 }
Ejemplo n.º 12
0
 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);
 }
Ejemplo n.º 13
0
 public MockHttpContext(string relativeUrl, Models.UserPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems)
 {
     _relativeUrl = relativeUrl;
     _principal = principal;
     _formParams = formParams;
     _queryStringParams = queryStringParams;
     _cookies = cookies;
     _sessionItems = sessionItems;
 }
Ejemplo n.º 14
0
 public FakeHttpContext(string relativeUrl, FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems)
 {
     this.relativeUrl = relativeUrl;
     this.principal = principal;
     this.formParams = formParams;
     this.queryStringParams = queryStringParams;
     this.cookies = cookies;
     this.sessionItems = sessionItems;
 }
Ejemplo n.º 15
0
 private byte[] Serialize(SessionStateItemCollection items)
 {
   MemoryStream ms = new MemoryStream();
   BinaryWriter writer = new BinaryWriter(ms);
   if (items != null)
   {
     items.Serialize(writer);
   }
   writer.Close();
   return ms.ToArray();
 }
Ejemplo n.º 16
0
		public FakeHttpContext(string relativeUrl, string method, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems)
		{
			this._relativeUrl = relativeUrl;
			this._method = method;
			this._principal = principal;
			this._formParams = formParams;
			this._queryStringParams = queryStringParams;
			this._cookies = cookies;
			this._sessionItems = sessionItems;
			this._items = new Dictionary<object, object>();
		}
 public object Deserialize(ObjectReader reader)
 {
     SessionStateItemCollection items = new SessionStateItemCollection();
     var count = reader.ReadInt32();
     for(int i = 0; i < count; i++)
     {
         var name = (string)reader.Deserialize();
         var value = reader.Deserialize();
         items[name] = value;
     }
     return items;
 }
 internal static SessionStateStoreData CreateLegitStoreData(HttpContext context, ISessionStateItemCollection sessionItems, HttpStaticObjectsCollection staticObjects, int timeout)
 {
     if (sessionItems == null)
     {
         sessionItems = new SessionStateItemCollection();
     }
     if ((staticObjects == null) && (context != null))
     {
         staticObjects = GetSessionStaticObjects(context);
     }
     return new SessionStateStoreData(sessionItems, staticObjects, timeout);
 }
 public FakeHttpContext(string url, FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems )
 {
     _url = url;
     _principal = principal;
     _formParams = formParams;
     _queryStringParams = queryStringParams;
     _cookies = cookies;
     _session = new FakeHttpSessionState(sessionItems);
     _request = new FakeHttpRequest(_url, _formParams, _queryStringParams, _cookies);
     _server = new FakeHttpServerUtility();
     _items = new Dictionary<string, object>();
 }
Ejemplo n.º 20
0
 public FakeControllerContext
     (
         ControllerBase controller,
         string userName,
         string[] roles,
         NameValueCollection formParams,
         NameValueCollection queryStringParams,
         HttpCookieCollection cookies,
         SessionStateItemCollection sessionItems
     )
     : base(new FakeHttpContext(new FakePrincipal(new FakeIdentity(userName), roles), formParams, queryStringParams, cookies, sessionItems), new RouteData(), controller)
 { }
Ejemplo n.º 21
0
		public FakeHttpContext(string relativeUrl, FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems)
		{
			_relativeUrl = relativeUrl;
			_principal = principal;
			_formParams = formParams;
			_queryStringParams = queryStringParams;
			_cookies = cookies;
			_sessionItems = sessionItems;
			_items = new HybridDictionary();

			_httpRequest = new FakeHttpRequest(_relativeUrl, _formParams, _queryStringParams, _cookies);
			_httpResponse = new FakeHttpResponse();
		}
        protected override SessionStateDocument PreExistingSessionState()
        {
            var items = new SessionStateItemCollection();
            items["Name"] = "Roger Ramjet";

            return new SessionStateDocument(SessionId, ApplicationName)
                {
                    Locked = false,
                    LockId = 3,
                    SessionItems = Subject.Serialize(items),
                    Expiry = DateTime.UtcNow.AddMinutes(8)
                };
        }
Ejemplo n.º 23
0
        public Mock<RandomBoardGenerator> createMock()
        {
            var moqBoardGenerator = new Mock<RandomBoardGenerator>();
            board = new Board(9);
            board.AddBombAt(1, 2);

            var session = new SessionStateItemCollection();
            session["board"] = board;
            moqBoardGenerator
                .Setup(x => x.Generate(It.IsAny<Func<ISizeOfBoard, Board>>()))
                .Returns(board);

            return moqBoardGenerator;
        }
Ejemplo n.º 24
0
        public static void BeforeTestRun()
        {
            IoCProvider.Initialize();

            SessionStateItemCollection sessionItems = new SessionStateItemCollection();

            IoCProvider.RegisterHttpSession(() => new FakeHttpSessionState(sessionItems));

            fixture = IoCProvider.Resolve<ITestFixtureSetup>();

            Settings.Instance = IoCProvider.Resolve<ISettings>();

            fixture.SetupTests();
        }
Ejemplo n.º 25
0
        public void ShouldReturnFalseWhenDoesntHaveBomb()
        {
            var moqBoardGenerator = createMock();
            var controller = new GameController(moqBoardGenerator.Object);
            int row = 1;
            int col = 2;
            board = new Board(9);
            var session = new SessionStateItemCollection();
            session["board"] = board;
            controller.ControllerContext = new FakeControllerContext(controller, session);

            var result = controller.HasBomb(row, col);
            Assert.IsFalse((bool)result.Data);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Session 정보를 직렬화합니다. (일반적인 직렬화 방식은 안되고, SessionStateItemCollection 자체의 Serialize를 사용해서 직렬화합니다.)
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static byte[] SerializeSessionState(SessionStateItemCollection items) {
            if(IsDebugEnabled)
                log.Debug("세션 정보를 직렬화를 수행합니다...");

            if(items == null)
                return new byte[0];

            using(var ms = new MemoryStream())
            using(var writer = new BinaryWriter(ms)) {
                items.Serialize(writer);
                writer.Close();

                return ms.ToArray();
            }
        }
Ejemplo n.º 27
0
        public FakeHttpContext(string relativeUrl, string method,
            IPrincipal principal, NameValueCollection formParams,
            NameValueCollection queryStringParams, HttpCookieCollection cookies,
            SessionStateItemCollection sessionItems, NameValueCollection serverVariables)
        {
            _relativeUrl = relativeUrl;
            _method = method;
            _principal = principal;
            _formParams = formParams;
            _queryStringParams = queryStringParams;
            _cookies = cookies;
            _sessionItems = sessionItems;
            _serverVariables = serverVariables;

            _items = new Hashtable();
        }
Ejemplo n.º 28
0
 public FakeControllerContext(
         IController controller,
         RouteData routeData,
         string relativeUrl,
         string userName,
         string[] roles,
         NameValueCollection formParams,
         NameValueCollection queryStringParams,
         HttpCookieCollection cookies,
         SessionStateItemCollection sessionItems
     )
     : base(new FakeHttpContext(relativeUrl, 
         new FakePrincipal(new FakeIdentity(userName), roles), 
         formParams, queryStringParams, cookies, sessionItems), routeData, controller as ControllerBase)
 {
 }
Ejemplo n.º 29
0
        public void FromSession_ShouldGetTheCartFromSession()
        {
            //Arrange
            var sessionItems = new SessionStateItemCollection();
            sessionItems.Dirty = false;
            sessionItems["cart"] = new ShoppingCart();

            var fakeHttpContext = FakeFactory.FakeHttpContextWithSession(sessionItems);

            var shoppingCartWrapper = new ShoppingCartWrapper(fakeHttpContext);

            //Act
            var shoppingCart = shoppingCartWrapper.Get();
            //Assert
            shoppingCart.Should().NotBeNull();
        }
Ejemplo n.º 30
0
        public void ShouldReturnTrueWhenCellHasBomb()
        {
            var session = new SessionStateItemCollection();
            board = new Board(9);
            board.AddBombAt(1, 2);
            session["board"] = board;

            var moqBoardGenerator = createMock();
            var controller = new GameController(moqBoardGenerator.Object);
            controller.ControllerContext = new FakeControllerContext(controller, session);
            int row = 1;
            int col = 2;

            JsonResult result = controller.HasBomb(row, col);
            Assert.IsTrue((bool)result.Data);
        }
Ejemplo n.º 31
0
        SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
        {
            MemoryStream ms = null;
            Stream       input;
            BinaryReader reader = null;
            GZipStream   gzip   = null;

            try {
                ms = new MemoryStream(Convert.FromBase64String(serializedItems));
                var sessionItems = new SessionStateItemCollection();

                if (ms.Length > 0)
                {
                    if (sessionConfig.CompressionEnabled)
                    {
                        input = gzip = new GZipStream(ms, CompressionMode.Decompress, true);
                    }
                    else
                    {
                        input = ms;
                    }

                    reader       = new BinaryReader(input);
                    sessionItems = SessionStateItemCollection.Deserialize(reader);
                    if (gzip != null)
                    {
                        gzip.Close();
                    }
                    reader.Close();
                }

                return(new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout));
            } finally {
                if (reader != null)
                {
                    reader.Dispose();
                }
                if (gzip != null)
                {
                    gzip.Dispose();
                }
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
Ejemplo n.º 32
0
        internal static SessionStateStoreData Deserialize(HttpContext context, Stream stream)
        {
            int timeout;
            SessionStateItemCollection sessionItems;
            bool hasItems;
            bool hasStaticObjects;
            HttpStaticObjectsCollection staticObjects;
            Byte eof;

            Debug.Assert(context != null);

            try {
                BinaryReader reader = new BinaryReader(stream);
                timeout          = reader.ReadInt32();
                hasItems         = reader.ReadBoolean();
                hasStaticObjects = reader.ReadBoolean();

                if (hasItems)
                {
                    sessionItems = SessionStateItemCollection.Deserialize(reader);
                }
                else
                {
                    sessionItems = new SessionStateItemCollection();
                }

                if (hasStaticObjects)
                {
                    staticObjects = HttpStaticObjectsCollection.Deserialize(reader);
                }
                else
                {
                    staticObjects = SessionStateUtility.GetSessionStaticObjects(context);
                }

                eof = reader.ReadByte();
                if (eof != 0xff)
                {
                    throw new HttpException(SR.GetString(SR.Invalid_session_state));
                }
            }
            catch (EndOfStreamException) {
                throw new HttpException(SR.GetString(SR.Invalid_session_state));
            }

            return(new SessionStateStoreData(sessionItems, staticObjects, timeout));
        }
Ejemplo n.º 33
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));
        }
Ejemplo n.º 34
0
        string Serialize(SessionStateItemCollection items)
        {
            GZipStream   gzip = null;
            Stream       output;
            MemoryStream ms     = null;
            BinaryWriter writer = null;

            try {
                ms = new MemoryStream();
                if (sessionConfig.CompressionEnabled)
                {
                    output = gzip = new GZipStream(ms, CompressionMode.Compress, true);
                }
                else
                {
                    output = ms;
                }
                writer = new BinaryWriter(output);

                if (items != null)
                {
                    items.Serialize(writer);
                }
                if (gzip != null)
                {
                    gzip.Close();
                }
                writer.Close();
                return(Convert.ToBase64String(ms.ToArray()));
            } finally {
                if (writer != null)
                {
                    writer.Dispose();
                }
                if (gzip != null)
                {
                    gzip.Dispose();
                }
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
        public static SessionStateItemCollection Deserialize(BinaryReader reader)
        {
            SessionStateItemCollection items = new SessionStateItemCollection();
            int count = reader.ReadInt32();

            if (count > 0)
            {
                int num3;
                int num2 = reader.ReadInt32();
                items._serializedItems = new KeyedCollection(count);
                for (num3 = 0; num3 < count; num3++)
                {
                    string str;
                    if (num3 == num2)
                    {
                        str = null;
                    }
                    else
                    {
                        str = reader.ReadString();
                    }
                    items.BaseSet(str, null);
                }
                int dataLength = reader.ReadInt32();
                items._serializedItems[items.BaseGetKey(0)] = new SerializedItemPosition(0, dataLength);
                int num5 = 0;
                for (num3 = 1; num3 < count; num3++)
                {
                    num5 = reader.ReadInt32();
                    items._serializedItems[items.BaseGetKey(num3)] = new SerializedItemPosition(dataLength, num5 - dataLength);
                    dataLength = num5;
                }
                items._iLastOffset = dataLength;
                byte[] buffer = new byte[items._iLastOffset];
                if (reader.BaseStream.Read(buffer, 0, items._iLastOffset) != items._iLastOffset)
                {
                    throw new HttpException(System.Web.SR.GetString("Invalid_session_state"));
                }
                items._stream = new MemoryStream(buffer);
            }
            items._dirty = false;
            return(items);
        }
        internal static SessionStateStoreData Deserialize(HttpContext context, Stream stream)
        {
            int num;
            SessionStateItemCollection  items;
            HttpStaticObjectsCollection sessionStaticObjects;

            try
            {
                BinaryReader reader = new BinaryReader(stream);
                num = reader.ReadInt32();
                bool flag  = reader.ReadBoolean();
                bool flag2 = reader.ReadBoolean();
                if (flag)
                {
                    items = SessionStateItemCollection.Deserialize(reader);
                }
                else
                {
                    items = new SessionStateItemCollection();
                }
                if (flag2)
                {
                    sessionStaticObjects = HttpStaticObjectsCollection.Deserialize(reader);
                }
                else
                {
                    sessionStaticObjects = GetSessionStaticObjects(context);
                }
                if (reader.ReadByte() != 0xff)
                {
                    throw new HttpException(System.Web.SR.GetString("Invalid_session_state"));
                }
            }
            catch (EndOfStreamException)
            {
                throw new HttpException(System.Web.SR.GetString("Invalid_session_state"));
            }
            return(new SessionStateStoreData(items, sessionStaticObjects, num));
        }
Ejemplo n.º 37
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);
        }
Ejemplo n.º 38
0
        public static SessionStateItemCollection Deserialize(BinaryReader reader)
        {
            SessionStateItemCollection d = new SessionStateItemCollection();
            int    count;
            int    nullKey;
            String key;
            int    i;

            byte[] buffer;

            count = reader.ReadInt32();

            if (count > 0)
            {
                nullKey = reader.ReadInt32();

                d._serializedItems = new KeyedCollection(count);

                // First, deserialize all the keys
                for (i = 0; i < count; i++)
                {
                    if (i == nullKey)
                    {
                        key = null;
                    }
                    else
                    {
                        key = reader.ReadString();
                    }

                    // Need to set them with null value first, so that
                    // the order of them items is correct.
                    d.BaseSet(key, null);
                }

                // Next, deserialize all the offsets
                // First offset will be 0, and the data length will be the first read offset
                int offset0 = reader.ReadInt32();
                d._serializedItems[d.BaseGetKey(0)] = new SerializedItemPosition(0, offset0);

                int offset1 = 0;
                for (i = 1; i < count; i++)
                {
                    offset1 = reader.ReadInt32();
                    d._serializedItems[d.BaseGetKey(i)] = new SerializedItemPosition(offset0, offset1 - offset0);
                    offset0 = offset1;
                }

                //
                d._iLastOffset = offset0;

                Debug.Trace("SessionStateItemCollection",
                            "Deserialize: _iLastOffset= " + d._iLastOffset);

                // _iLastOffset is the first byte past the last item, which equals
                // the total length of all serialized data
                buffer = new byte[d._iLastOffset];
                int bytesRead = reader.BaseStream.Read(buffer, 0, d._iLastOffset);
                if (bytesRead != d._iLastOffset)
                {
                    throw new HttpException(SR.GetString(SR.Invalid_session_state));
                }
                d._stream = new MemoryStream(buffer);
            }

    #if DBG
            Debug.Assert(reader.ReadByte() == 0xff);
    #endif

            d._dirty = false;

            return(d);
        }
Ejemplo n.º 39
0
		SessionStateStoreData GetItemInternal (HttpContext context,
						       string id,
						       out bool locked,
						       out TimeSpan lockAge,
						       out object lockId,
						       out SessionStateActions actions,
						       bool exclusive)
		{
			locked = false;
			lockAge = TimeSpan.MinValue;
			lockId = Int32.MinValue;
			actions = SessionStateActions.None;

			if (id == null)
				return null;
			
			StateServerItem item = stateServer.GetItem (id,
								    out locked,
								    out lockAge,
								    out lockId,
								    out actions,
								    exclusive);
			
			if (item == null)
				return null;
			
			if (actions == SessionStateActions.InitializeItem)
				return CreateNewStoreData (context, item.Timeout);
			
			SessionStateItemCollection items = null;
			HttpStaticObjectsCollection sobjs = null;
			MemoryStream stream = null;
			BinaryReader reader = null;
			Stream input = null;
#if NET_4_0
			GZipStream gzip = null;
#endif
			try {
				if (item.CollectionData != null && item.CollectionData.Length > 0) {
					stream = new MemoryStream (item.CollectionData);
#if NET_4_0					
					if (config.CompressionEnabled)
						input = gzip = new GZipStream (stream, CompressionMode.Decompress, true);
					else
#endif
						input = stream;
					reader = new BinaryReader (input);
					items = SessionStateItemCollection.Deserialize (reader);
#if NET_4_0
					if (gzip != null)
						gzip.Close ();
#endif
					reader.Close ();
				} else
					items = new SessionStateItemCollection ();
				if (item.StaticObjectsData != null && item.StaticObjectsData.Length > 0)
					sobjs = HttpStaticObjectsCollection.FromByteArray (item.StaticObjectsData);
				else
					sobjs = new HttpStaticObjectsCollection ();
			} catch (Exception ex) {
				throw new HttpException ("Failed to retrieve session state.", ex);
			} finally {
				if (stream != null)
					stream.Dispose ();
#if NET_4_0
				if (reader != null)
					reader.Dispose ();
				if (gzip != null)
					gzip.Dispose ();
#else
				if (reader != null)
					((IDisposable)reader).Dispose ();
#endif
			}
				
			return new SessionStateStoreData (items,
							  sobjs,
							  item.Timeout);
		}
Ejemplo n.º 40
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);
        }
Ejemplo n.º 41
0
        SessionStateStoreData GetItemInternal(HttpContext context,
                                              string id,
                                              out bool locked,
                                              out TimeSpan lockAge,
                                              out object lockId,
                                              out SessionStateActions actions,
                                              bool exclusive)
        {
            Trace.WriteLine("SessionStateServerHandler.GetItemInternal");
            Trace.WriteLine("\tid == " + id);
            Trace.WriteLine("\tpath == " + context.Request.FilePath);
            locked  = false;
            lockAge = TimeSpan.MinValue;
            lockId  = Int32.MinValue;
            actions = SessionStateActions.None;

            if (id == null)
            {
                return(null);
            }

            StateServerItem item = stateServer.GetItem(id,
                                                       out locked,
                                                       out lockAge,
                                                       out lockId,
                                                       out actions,
                                                       exclusive);

            if (item == null)
            {
                Trace.WriteLine("\titem is null (locked == " + locked + ", actions == " + actions + ")");
                return(null);
            }
            if (actions == SessionStateActions.InitializeItem)
            {
                Trace.WriteLine("\titem needs initialization");
                return(CreateNewStoreData(context, item.Timeout));
            }
            SessionStateItemCollection  items = null;
            HttpStaticObjectsCollection sobjs = null;
            MemoryStream stream = null;
            BinaryReader reader = null;

            try {
                if (item.CollectionData != null && item.CollectionData.Length > 0)
                {
                    stream = new MemoryStream(item.CollectionData);
                    reader = new BinaryReader(stream);
                    items  = SessionStateItemCollection.Deserialize(reader);
                }
                else
                {
                    items = new SessionStateItemCollection();
                }
                if (item.StaticObjectsData != null && item.StaticObjectsData.Length > 0)
                {
                    sobjs = HttpStaticObjectsCollection.FromByteArray(item.StaticObjectsData);
                }
                else
                {
                    sobjs = new HttpStaticObjectsCollection();
                }
            } catch (Exception ex) {
                throw new HttpException("Failed to retrieve session state.", ex);
            } finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(new SessionStateStoreData(items,
                                             sobjs,
                                             item.Timeout));
        }