Exemplo n.º 1
0
        public void TestCountLock()
        {
            var countLock = new CountLock();

            countLock.Reset(2);
            Assert.IsTrue(countLock.TryRetain(2));
            Assert.IsFalse(countLock.TryRetain(2));
        }
        public override void OnActionExecuting(ActionExecutingContext executingContext)
        {
            var key        = string.Concat(Name, "-", GetIpAddress());
            var countLock  = new CountLock();
            var castLocked = HttpRuntime.Cache[key] as CountLock;

            if (castLocked != null && castLocked.IsLocked)
            {
                executingContext.Controller.ViewBag.Locked       = true;
                executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
            }

            else
            {
                var cacheExperation = TimeLimit;
                countLock.Count    = 1;
                countLock.IsLocked = false;

                if (castLocked != null)
                {
                    countLock.Count = castLocked.Count + 1;
                    if (countLock.Count > Attempts)
                    {
                        cacheExperation    = TimeWait;
                        countLock.IsLocked = true;

                        executingContext.Controller.ViewBag.Locked       = true;
                        executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
                    }
                }

                HttpRuntime.Cache.Insert(key,
                                         countLock,
                                         null,
                                         DateTime.Now.AddMinutes(cacheExperation),
                                         Cache.NoSlidingExpiration,
                                         CacheItemPriority.Low, null);
            }
        }