示例#1
0
            public static CookieSessionState FromJson(string json)
            {
                if (string.IsNullOrEmpty(json))
                {
                    return(null);
                }

                try
                {
                    SessionStateItem item =
                        (new JavaScriptSerializer()).Deserialize <SessionStateItem>(HttpUtility.UrlDecode(json));


                    SessionStateItemCollection collections = new SessionStateItemCollection();

                    foreach (KeyValuePair <string, object> kvp in item.Dict)
                    {
                        collections[kvp.Key] = kvp.Value;
                    }

                    return(new CookieSessionState(collections, null, item.Timeout));
                }
                catch
                {
                    return(null);
                }
            }
            private static SessionStateItem LoadItem(MemoryStream ms)
            {
                var graph = new ObjectStateFormatter().Deserialize(ms) as Pair;

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

                if (((byte)graph.First) != 1)
                {
                    return(null);
                }

                var t      = (Triplet)graph.Second;
                var retval = new SessionStateItem();

                retval.Flag    = (SessionStateActions)((byte)t.First);
                retval.Timeout = (int)t.Second;

                var lockInfo = (Pair)t.Third;

                retval.LockId   = (ulong)lockInfo.First;
                retval.LockTime = DateTime.FromBinary((long)lockInfo.Second);

                return(retval);
            }
示例#3
0
            public string ToJson()
            {
                // 这里忽略_staticObjects这个成员。

                if (_sessionItems == null || _sessionItems.Count == 0)
                {
                    return(null);
                }

                Dictionary <string, object> dict = new Dictionary <string, object>(_sessionItems.Count);

                string key;

                NameObjectCollectionBase.KeysCollection keys = _sessionItems.Keys;
                for (int i = 0; i < keys.Count; i++)
                {
                    key = keys[i];
                    dict.Add(key, _sessionItems[key]);
                }

                SessionStateItem item = new SessionStateItem {
                    Dict = dict, Timeout = this._timeout
                };

                return(HttpUtility.UrlEncode((new JavaScriptSerializer()).Serialize(item)));

                // 由于使用Dictionary<string, object>类型,造成复杂类型在序列化时就丢失了它们的类型信息,
                // 因此,在下面的反序列化时,就不能还原正原的类型。
                // 也正是因为此原因,CookieSessionStateStore只适合保存简单的基元类型数据。
            }
        private SessionStateItem Get(HttpContext context, bool acquireLock, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
        {
            locked  = false;
            lockId  = null;
            lockAge = TimeSpan.Zero;
            actions = SessionStateActions.None;

            var e = SessionStateItem.Load(this.client, id, false);

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

            if (acquireLock)
            {
                // repeat until we can update the retrieved
                // item (i.e. nobody changes it between the
                // time we get it from the store and updates its attributes)
                // Save() will return false if Cas() fails
                while (true)
                {
                    if (e.LockId > 0)
                    {
                        break;
                    }

                    actions = e.Flag;

                    e.LockId   = e.HeadCas;
                    e.LockTime = DateTime.UtcNow;
                    e.Flag     = SessionStateActions.None;

                    // try to update the item in the store
                    if (e.Save(this.client, id, true, true))
                    {
                        locked = true;
                        lockId = e.LockId;

                        return(e);
                    }

                    // it has been modifed between we loaded and tried to save it
                    e = SessionStateItem.Load(this.client, id, false);
                    if (e == null)
                    {
                        return(null);
                    }
                }
            }

            locked  = true;
            lockAge = DateTime.UtcNow - e.LockTime;
            lockId  = e.LockId;
            actions = SessionStateActions.None;

            return(acquireLock ? null : e);
        }
        public override void ResetItemTimeout(HttpContext context, string id)
        {
            var e = SessionStateItem.Load(this.client, id, false);

            if (e != null)
            {
                e.Save(this.client, id, false, true);
            }
        }
        public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
        {
            var e = new SessionStateItem
            {
                Data = new SessionStateItemCollection(),
                Flag = SessionStateActions.InitializeItem,
                LockId = 0,
                Timeout = timeout
            };

            e.Save(_client, id, false, false);
        }
        public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
        {
            var e = new SessionStateItem
            {
                Data    = new SessionStateItemCollection(),
                Flag    = SessionStateActions.InitializeItem,
                LockId  = 0,
                Timeout = timeout
            };

            e.Save(this.client, id, false, false);
        }
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            if (!(lockId is ulong))
            {
                return;
            }

            var tmp = (ulong)lockId;
            var e   = SessionStateItem.Load(this.client, id, true);

            if (e != null && e.LockId == tmp)
            {
                SessionStateItem.Remove(this.client, id);
            }
        }
示例#9
0
        public void Load_WhenNotSuccess_ReturnNull(ResponseStatus status)
        {
            //arrange
            var result = new Mock <IOperationResult <byte[]> >();

            result.Setup(x => x.Status).Returns(status);

            var bucket = new Mock <IBucket>();

            bucket.Setup(x => x.Get <byte[]>(It.IsAny <string>())).Returns(result.Object);

            //act
            var item = SessionStateItem.Load(bucket.Object, "thekey", false);

            //assert
            Assert.IsNull(item);
        }
        public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
        {
            if (!(lockId is ulong))
            {
                return;
            }

            var tmp = (ulong)lockId;
            var e   = SessionStateItem.Load(this.client, id, true);

            if (e != null && e.LockId == tmp)
            {
                e.LockId   = 0;
                e.LockTime = DateTime.MinValue;

                e.Save(this.client, id, true, true);
            }
        }
        public void SessionStateItem_Can_Be_Serialized_With_LockAge()
        {
            var item = new SessionStateItem()
            {
                Actions     = SessionStateActions.InitializeItem,
                LockAge     = TimeSpan.FromMinutes(1),
                LockCookie  = 1,
                Locked      = true,
                SessionId   = TestSessionId,
                SessionItem = new byte[2] {
                    1, 1
                },
                Timeout = 10
            };
            var json     = JsonConvert.SerializeObject(item);
            var expected = string.Format(JsonTemplate, item.SessionId, 60 * 1, item.LockCookie, item.Timeout, item.Locked, "AQE=", false);

            Assert.Equal(expected, json, true);
        }
        public void SessionStateItem_Can_Be_Serialized_With_Null_LockAge()
        {
            var item = new SessionStateItem()
            {
                Actions     = SessionStateActions.None,
                LockAge     = null,
                LockCookie  = 1,
                Locked      = false,
                SessionId   = TestSessionId,
                SessionItem = new byte[2] {
                    1, 1
                },
                Timeout = 10
            };
            var json     = JsonConvert.SerializeObject(item);
            var expected = string.Format(JsonTemplate, item.SessionId, "null", item.LockCookie, item.Timeout, item.Locked, "AQE=", true);

            Assert.Equal(expected, json, true);
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            SessionStateItem e        = null;
            bool             existing = false;

            if (!newItem)
            {
                if (!(lockId is ulong))
                {
                    return;
                }

                var tmp = (ulong)lockId;
                e        = SessionStateItem.Load(this.client, id, true);
                existing = e != null;

                // if we're expecting an existing item, but
                // it's not in the cache
                // or it's not locked
                // or it's locked by someone else, then quit
                if (!newItem &&
                    (!existing ||
                     e.LockId == 0 ||
                     e.LockId != tmp))
                {
                    return;
                }
            }

            if (!existing)
            {
                e = new SessionStateItem();
            }

            // set the new data and reset the locks
            e.Timeout  = item.Timeout;
            e.Data     = (SessionStateItemCollection)item.Items;
            e.Flag     = SessionStateActions.None;
            e.LockId   = 0;
            e.LockTime = DateTime.MinValue;

            e.Save(this.client, id, false, existing && !newItem);
        }
            public static SessionStateItem Load(IMemcachedClient client, string id, bool metaOnly)
            {
                var header = client.GetWithCas <byte[]>(HeaderPrefix + id);

                if (header.Result == null)
                {
                    return(null);
                }

                SessionStateItem entry;

                using (var ms = new MemoryStream(header.Result))
                    entry = SessionStateItem.LoadItem(ms);

                if (entry != null)
                {
                    entry.HeadCas = header.Cas;
                }
                if (metaOnly)
                {
                    return(entry);
                }

                var data = client.GetWithCas <byte[]>(DataPrefix + id);

                if (data.Result == null)
                {
                    return(null);
                }

                using (var ms = new MemoryStream(data.Result))
                    using (var br = new BinaryReader(ms))
                        entry.Data = SessionStateItemCollection.Deserialize(br);

                entry.DataCas = data.Cas;

                return(entry);
            }
            private static SessionStateItem LoadItem(MemoryStream ms)
            {
                var graph = new ObjectStateFormatter().Deserialize(ms) as Pair;
                if (graph == null) return null;

                if (((byte)graph.First) != 1) return null;

                var t = (Triplet)graph.Second;
                var retval = new SessionStateItem();

                retval.Flag = (SessionStateActions)((byte)t.First);
                retval.Timeout = (int)t.Second;

                var lockInfo = (Pair)t.Third;

                retval.LockId = (ulong)lockInfo.First;
                retval.LockTime = DateTime.FromBinary((long)lockInfo.Second);

                return retval;
            }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            SessionStateItem e = null;
            bool existing = false;

            if (!newItem)
            {
                if (!(lockId is ulong))
                    return;

                var tmp = (ulong)lockId;
                e = SessionStateItem.Load(_client, id, true);
                existing = e != null;

                // if we're expecting an existing item, but
                // it's not in the cache
                // or it's not locked
                // or it's locked by someone else, then quit
                if (!existing
                        || e.LockId == 0
                        || e.LockId != tmp)
                    return;
            }

            if (!existing) e = new SessionStateItem();

            // set the new data and reset the locks
            e.Timeout = item.Timeout;
            e.Data = (SessionStateItemCollection)item.Items;
            e.Flag = SessionStateActions.None;
            e.LockId = 0;
            e.LockTime = DateTime.MinValue;

            e.Save(_client, id, false, existing && !newItem);
        }