Inheritance: MethodInterceptionAspect
Example #1
0
        public CacheAttributeTests()
        {
            _cacheProvider      = A.Fake <ICacheProvider>();
            _licenseSettings    = A.Fake <ILicenseSettings>();
            _dependencyResolver = A.Fake <Func <HttpActionContext, Type, object> >();
            _cacheAttribute     = new CacheAttribute(_cachedHours, _dependencyResolver);
            _request            = new HttpRequestMessage();

            HttpControllerContext httpControllerContext = new HttpControllerContext
            {
                Request       = _request,
                Configuration = new HttpConfiguration()
            };

            _actionContext = new HttpActionContext
            {
                ControllerContext = httpControllerContext
            };

            HttpActionDescriptor httpActionDescriptor = A.Fake <HttpActionDescriptor>();

            _actionExecutedContext = new HttpActionExecutedContext
            {
                ActionContext = _actionContext
            };

            A.CallTo(() => _dependencyResolver(_actionContext, typeof(ICacheProvider))).Returns(_cacheProvider);
            A.CallTo(() => _dependencyResolver(_actionContext, typeof(ILicenseSettings))).Returns(_licenseSettings);
            A.CallTo(() => _licenseSettings.ApplicationName).Returns("testapplication");
        }
Example #2
0
        public void OutputCacheVaryByParams()
        {
            ClearCache();

            CacheAttribute readController = new CacheAttribute
            {
                CacheOnServer = true,
                VarByParams   = "id,lang"
            };
            CacheAttribute updateController = new CacheAttribute
            {
                CacheOnServer = true,
                Update        = true,
                VarByParams   = "id,lang"
            };

            Uri uri1 = new Uri("http://epiwiki.se/?id=1&lang=sv");
            Uri uri2 = new Uri("http://epiwiki.se/?id=2&lang=sv");

            // first browser should load the cache
            new Browser(uri1).MakeRequest(readController);

            // The second request should read from cace
            Browser browser = new Browser(uri1);

            browser.MakeRequest(readController);
            Assert.IsFalse(browser.ControllerExecuted);

            // The first request to the other id should update the cace
            Browser browser1 = new Browser(uri2);

            browser1.MakeRequest(readController);
            Assert.IsTrue(browser1.ControllerExecuted);
        }
Example #3
0
        public void Add <TValue>(bool saveAttribute, bool saveGet, bool saveSet, bool saveProperties)
        {
            string typeName = typeof(TValue).Name;

            PropertyInfo[] properties = typeof(TValue).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

            if (saveGet && !CacheGet.ContainsKey(typeName))
            {
                CacheGet.Add(typeName, properties.ToDictionary(g => g.Name, m => CacheFacade.CreateFunction <TValue>(m)));
            }
            if (saveSet && !CacheSet.ContainsKey(typeName))
            {
                CacheSet.Add(typeName, properties.ToDictionary(s => s.Name, m => CacheFacade.CreateAction <TValue>(m)));
            }
            if (saveProperties && !CacheProperties.ContainsKey(typeName))
            {
                CacheProperties.Add(typeName, properties.ToDictionary(p => p.Name, p => p));
            }
            if (saveAttribute && !CacheAttribute.ContainsKey(typeName))
            {
                CacheAttribute.Add(typeName, new Dictionary <string, Dictionary <string, CustomAttributeTypedArgument> >(properties.Length));
                foreach (var property in properties)
                {
                    CachingAttribute(property, typeName);
                }
            }
        }
Example #4
0
        // 生成缓存值的键值
        private string GetValueKey(CacheAttribute cachingAttribute, IMethodInvocation input)
        {
            switch (cachingAttribute.Method)
            {
            // 如果是Remove,则不存在特定值键名,所有的以该方法名称相关的缓存都需要清除
            case CachingMethod.Remove:
                return(null);

            // 如果是Get或者Update,则需要产生一个针对特定参数值的键名
            case CachingMethod.Get:
            case CachingMethod.Update:
                if (input.Arguments != null &&
                    input.Arguments.Count > 0)
                {
                    var sb = new StringBuilder();
                    for (var i = 0; i < input.Arguments.Count; i++)
                    {
                        sb.Append(input.Arguments[i]);
                        if (i != input.Arguments.Count - 1)
                        {
                            sb.Append("_");
                        }
                    }

                    return(sb.ToString());
                }
                else
                {
                    return("NULL");
                }

            default:
                throw new InvalidOperationException("无效的缓存方式。");
            }
        }
Example #5
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            CacheAttribute attr = input.MethodBase.GetCustomAttribute <CacheAttribute>();

            if (attr == null)
            {
                return(getNext()(input, getNext));
            }
            var    arguments  = input.MethodBase.GetParameters().ToString(input);
            string key        = $"{arguments}";
            string methodName = $"{input.MethodBase.Name}|{input.MethodBase.DeclaringType.FullName}";
            var    mc         = Cache.GetOrAdd(methodName, x => { return(new MemoryCache(x)); });
            var    data       = mc.Get(key);

            if (data != null)
            {
                return(input.CreateMethodReturn(data));
            }
            IMethodReturn result = getNext()(input, getNext);

            if (result.ReturnValue == null)
            {
                return(result);
            }
            mc.Add(key, result.ReturnValue, new CacheItemPolicy {
                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(attr.CacheTime))
            });
            return(result);
        }
Example #6
0
 public void ExecuteControllerAction(CacheAttribute filter)
 {
     _controllerExecuted            = true;
     actionExecutedContext.Response = new HttpResponseMessage();
     actionExecutedContext.Response.RequestMessage = actionExecutingContext.Request;
     filter.OnActionExecuted(actionExecutedContext);
 }
Example #7
0
        public void ETagUpdateForUser()
        {
            CacheAttribute filter = new CacheAttribute {
                VaryByUser = true
            };
            CacheAttribute updateFilter = new CacheAttribute {
                VaryByUser = true,
                Update     = true
            };
            IPrincipal principal  = new GenericPrincipal(new GenericIdentity("user1"), new string[] { "role1", "role2" });
            IPrincipal principal2 = new GenericPrincipal(new GenericIdentity("user2"), new string[] { "role1", "role3" });

            Thread.CurrentPrincipal = principal;
            Browser browser = new Browser();

            //First request update cace for principal1
            browser.MakeRequest(filter);
            Thread.CurrentPrincipal = principal2;
            Browser browser2 = new Browser();

            //First request update cache for principal2
            browser2.MakeRequest(filter);
            EntityTagHeaderValue eTag = browser2.ETag;

            Assert.AreNotEqual <EntityTagHeaderValue>(browser.ETag, browser2.ETag);
            //Make Update should invalidate for all since it not marked VaryByUser
            browser2.MakeRequest(updateFilter);
            //Make normal request
            browser2.MakeRequest(filter);
            Assert.AreNotEqual <EntityTagHeaderValue>(eTag, browser2.ETag);
        }
Example #8
0
        public void ETagCacheVaryByParams()
        {
            ServerCache.ClearCache();

            CacheAttribute readController = new CacheAttribute
            {
                VarByParams = "id,lang"
            };
            CacheAttribute updateController = new CacheAttribute
            {
                Update      = true,
                VarByParams = "id,lang"
            };

            Uri uri1 = new Uri("http://epiwiki.se/?id=1&lang=sv");
            Uri uri2 = new Uri("http://epiwiki.se/?id=2&lang=sv");
            Uri uri3 = new Uri("http://epiwiki.se/?id=2&lang=sv&notincluded=true");

            // first url should get a etag
            var browser1 = new Browser(uri1);

            browser1.MakeRequest(readController);

            // second url should get another etag
            var browser2 = new Browser(uri2);

            browser2.MakeRequest(readController);
            Assert.AreNotEqual(browser1.ETag, browser2.ETag);

            // second url should get another etag
            var browser3 = new Browser(uri3);

            browser3.MakeRequest(readController);
            Assert.AreEqual(browser2.ETag, browser3.ETag);
        }
Example #9
0
        public void OutputCacheDeliverCachedDuringUpdate()
        {
            ClearCache();

            CacheAttribute readController = new CacheAttribute {
                CacheOnServer = true
            };
            CacheAttribute updateController = new CacheAttribute {
                CacheOnServer = true,
                Update        = true
            };

            // first browser should load the cache
            new Browser().MakeRequest(readController);

            // The second request flag the cache for updates
            Browser updateBrowser = new Browser();

            updateController.OnActionExecuting(updateBrowser.ActionExecutingContext);

            // the third request should deliver old content from cache
            Browser browser2 = new Browser();

            browser2.MakeRequest(readController);
            Assert.IsFalse(browser2.ControllerExecuted);

            //Make the request
            updateBrowser.ExecuteControllerAction(readController);
            // The second request updates the cache
            updateController.OnActionExecuted(updateBrowser.ActionExecutedContext);
        }
Example #10
0
        public void WhenExecutingFilterWithoutContextThenThrowsArgumentNullException()
        {
            // Arrange
            CacheAttribute filter = this.CreateAttribute();

            // Act & Assert
            ExceptionAssert.ThrowsArgumentNull(() => filter.OnCommandExecuting(null), "CommandHandlerContext");
        }
Example #11
0
 public void MakeRequest(CacheAttribute filter)
 {
     filter.OnActionExecuting(actionExecutingContext);
     if (actionExecutingContext.Response == null)
     {
         ExecuteControllerAction(filter);
     }
 }
Example #12
0
        public void WhenSettingNullToVaryByParamsThenThrowsArgumentNullException()
        {
            // Arrange
            CacheAttribute filter = this.CreateAttribute();

            // Act & assert
            ExceptionAssert.Throws <ArgumentNullException>(() => filter.VaryByParams = null);
        }
Example #13
0
        public void WhenExecutedFilterVaryByUserThenCacheIsUpdated()
        {
            // Arrange
            CacheAttribute filter = this.CreateAttribute(new MemoryCache("test"));

            filter.Duration     = 10;
            filter.VaryByUser   = true;
            filter.VaryByParams = CacheAttribute.VaryByParamsNone;

            CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler));
            SimpleCommand            command1   = new SimpleCommand {
                Property1 = 1, Property2 = "test1"
            };
            CommandHandlerRequest request1 = new CommandHandlerRequest(this.config, command1);
            CommandHandlerContext context1 = new CommandHandlerContext(request1, descriptor);

            context1.User = new GenericPrincipal(new GenericIdentity("user1"), null);
            CommandHandlerExecutedContext executedContext1 = new CommandHandlerExecutedContext(context1, null);

            executedContext1.Response = new HandlerResponse(request1, "result1");

            SimpleCommand command2 = new SimpleCommand {
                Property1 = 1, Property2 = "test1"
            };
            CommandHandlerRequest request2 = new CommandHandlerRequest(this.config, command2);
            CommandHandlerContext context2 = new CommandHandlerContext(request2, descriptor);

            context2.User = new GenericPrincipal(new GenericIdentity("user2"), null);
            CommandHandlerExecutedContext executedContext2 = new CommandHandlerExecutedContext(context2, null);

            executedContext2.Response = new HandlerResponse(request2, "result2");

            SimpleCommand command3 = new SimpleCommand {
                Property1 = 1, Property2 = "test1"
            };
            CommandHandlerRequest request3 = new CommandHandlerRequest(this.config, command3);
            CommandHandlerContext context3 = new CommandHandlerContext(request3, descriptor);

            context3.User = new GenericPrincipal(new GenericIdentity("user1"), null);
            CommandHandlerExecutedContext executedContext3 = new CommandHandlerExecutedContext(context3, null);

            executedContext3.Response = new HandlerResponse(request3, "result3");

            // Act
            filter.OnCommandExecuting(context1);
            filter.OnCommandExecuted(executedContext1);
            filter.OnCommandExecuting(context2);
            filter.OnCommandExecuted(executedContext2);
            filter.OnCommandExecuting(context3);
            filter.OnCommandExecuted(executedContext3);

            // Assert
            Assert.Equal("result1", executedContext1.Response.Value);
            Assert.Equal("result2", executedContext2.Response.Value);
            Assert.Equal("result1", executedContext3.Response.Value);
        }
Example #14
0
        private static DateTimeOffset ComputeExpiration(CacheAttribute cacheAttribute)
        {
            var minutes = cacheAttribute.Minutes;

            if (minutes < 1)
            {
                minutes = 5;
            }
            return(DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(minutes)));
        }
        public async Task OnActionExecutionAsync_CacheValue()
        {
            CacheAttribute cacheAttribute = new CacheAttribute(10);

            _cachingServiceMock.Setup(x => x.Get(It.IsAny <string>())).Returns(null);
            await cacheAttribute.OnActionExecutionAsync(_actionExecutingContext, () => Task.FromResult(_context));

            _cachingServiceMock.Verify(x => x.Get(It.IsAny <string>()), Times.Once());
            _cachingServiceMock.Verify(x => x.Put(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <TimeSpan>()), Times.Once());
        }
        /// <summary>
        /// Adds caching capabilities for the method with the given name of the given service type.
        /// </summary>
        /// <typeparam name="TService">The service type.</typeparam>
        /// <param name="methodNameFactory">The method name factory. Example usage: CacheOptions.AddCache&lt;IMyService&gt;(x =&gt; nameof(x.GetAll))</param>
        /// <param name="configure">Optional method cache options.</param>
        /// <returns>The <see cref="CacheOptionsConfiguration"/> to use for further configuration.</returns>
        public CacheOptionsConfiguration AddCache <TService>(Func <TService, string> methodNameFactory, Action <IMethodCacheOptions> configure)
        {
            var serviceType        = typeof(TService);
            var methodCacheOptions = GetOrAddMethodCacheOptions(serviceType);

            var cacheAttribute = new CacheAttribute();

            configure.Invoke(cacheAttribute);

            var methodName = methodNameFactory.Invoke(default);
Example #17
0
        /// <summary>
        /// 执行,按实际结果返回
        /// </summary>
        /// <param name="letter">客户端递交的参数信息</param>
        /// <returns></returns>
        public static object Exec(Letter letter)
        {
            //1.创建对象,即$api.get("account/single")中的account
            IViewAPI execObj = ExecuteMethod.CreateInstance(letter);
            //2.获取要执行的方法,即$api.get("account/single")中的single
            MethodInfo method = getMethod(execObj.GetType(), letter);

            //清除缓存
            if (letter.HTTP_METHOD.Equals("put", StringComparison.CurrentCultureIgnoreCase))
            {
                CacheAttribute.Remove(method, letter);
            }
            //3#.验证方法的特性,一是验证Http动词,二是验证是否登录后操作,三是验证权限
            //----验证Http谓词访问限制
            HttpAttribute.Verify(letter.HTTP_METHOD, method);
            //LoginAttribute.Verify(method);
            //----范围控制,本机或局域网,或同域
            bool isRange = RangeAttribute.Verify(method, letter);
            //----验证是否需要登录
            LoginAttribute loginattr = LoginAttribute.Verify(method, letter);

            //----清理参数值中的html标签,默认全部清理,通过设置not参数不过虑某参数
            HtmlClearAttribute.Clear(method, letter);


            //4.构建执行该方法所需要的参数
            object[] parameters = getInvokeParam(method, letter);
            //5.执行方法,返回结果
            object objResult = null;    //结果
            //只有get方式时,才使用缓存
            CacheAttribute cache = null;

            //if (letter.HTTP_METHOD.Equals("put", StringComparison.CurrentCultureIgnoreCase))
            //    CacheAttribute.Remove(method, letter);
            if (letter.HTTP_METHOD.Equals("get", StringComparison.CurrentCultureIgnoreCase))
            {
                cache = CacheAttribute.GetAttr <CacheAttribute>(method);
            }
            if (cache != null)
            {
                objResult = CacheAttribute.GetResult(method, letter);
                if (objResult == null)
                {
                    objResult = method.Invoke(execObj, parameters);
                    CacheAttribute.Insert(cache.Expires, method, letter, objResult);
                }
            }
            else
            {
                objResult = method.Invoke(execObj, parameters);
            }
            //将执行结果写入日志
            LoginAttribute.LogWrite(loginattr, objResult);
            return(objResult);
        }
Example #18
0
        private bool CanCache()
        {
            var            t  = typeof(T);
            CacheAttribute ca = t.DeclaringType.GetTypeInfo().GetCustomAttribute <CacheAttribute>();

            if (ca == null)
            {
                return(false);
            }
            return(true);
        }
Example #19
0
        public void ETagNotUpdate()
        {
            CacheAttribute filter  = new CacheAttribute();
            Browser        browser = new Browser();

            browser.MakeRequest(filter);
            Assert.IsTrue(browser.ETag != null);
            browser = new Browser(browser.ETag);
            browser.MakeRequest(filter);
            Assert.IsTrue(browser.StatusCode == HttpStatusCode.NotModified);
        }
Example #20
0
        private object GetFromCacheAndRefreshExpiration(string cacheKey, Type type, CacheAttribute cacheAttribute)
        {
            var cachedValue = _cache.Get(cacheKey, type);

            if (cacheAttribute.IsSlidingExpiration)
            {
                _cache.SetExpirationTime(cacheKey, cacheAttribute.TTL);
            }

            return(cachedValue);
        }
Example #21
0
        public void ETagFullRequest()
        {
            CacheAttribute filter  = new CacheAttribute();
            Browser        browser = new Browser();

            browser.MakeRequest(filter);
            Assert.IsTrue(!string.IsNullOrEmpty(browser.ActionExecutedContext.Response.Headers.ETag.Tag));
            Assert.IsTrue(browser.StatusCode == HttpStatusCode.OK);
            browser = new Browser(browser.ETag);
            browser.MakeRequest(filter);
            Assert.IsTrue(browser.StatusCode == HttpStatusCode.NotModified);
        }
Example #22
0
        public void alter_chain()
        {
            var att   = new CacheAttribute();
            var chain = new BehaviorChain();
            var call  = ActionCall.For <CacheAttributeTester>(x => x.alter_chain());

            chain.AddToEnd(call);

            att.Alter(call);

            chain.OfType <OutputCachingNode>().Single()
            .VaryByPolicies().Single().ShouldEqual(typeof(VaryByResource));
        }
Example #23
0
        public void WhenExecutedFilterVaryByParamsSetIncorrectlyThenCacheIsAlwaysUsed()
        {
            // Arrange
            CacheAttribute filter = this.CreateAttribute(new MemoryCache("test"));

            filter.Duration     = 10;
            filter.VaryByParams = "XXXX";

            CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler));
            SimpleCommand            command1   = new SimpleCommand {
                Property1 = 1, Property2 = "test1"
            };
            CommandHandlerRequest         request1         = new CommandHandlerRequest(this.config, command1);
            CommandHandlerContext         context1         = new CommandHandlerContext(request1, descriptor);
            CommandHandlerExecutedContext executedContext1 = new CommandHandlerExecutedContext(context1, null);

            executedContext1.SetResponse("result1");

            SimpleCommand command2 = new SimpleCommand {
                Property1 = 2, Property2 = "test2"
            };
            CommandHandlerRequest         request2         = new CommandHandlerRequest(this.config, command2);
            CommandHandlerContext         context2         = new CommandHandlerContext(request2, descriptor);
            CommandHandlerExecutedContext executedContext2 = new CommandHandlerExecutedContext(context2, null);

            executedContext2.SetResponse("result2");

            SimpleCommand command3 = new SimpleCommand {
                Property1 = 2, Property2 = "test3"
            };
            CommandHandlerRequest         request3         = new CommandHandlerRequest(this.config, command3);
            CommandHandlerContext         context3         = new CommandHandlerContext(request3, descriptor);
            CommandHandlerExecutedContext executedContext3 = new CommandHandlerExecutedContext(context3, null);

            executedContext3.SetResponse("result3");

            // Act
            filter.OnCommandExecuting(context1);
            filter.OnCommandExecuted(executedContext1);
            filter.OnCommandExecuting(context2);
            filter.OnCommandExecuted(executedContext2);
            filter.OnCommandExecuting(context3);
            filter.OnCommandExecuted(executedContext3);

            // Assert
            Assert.Equal("result1", executedContext1.Response.Value);
            Assert.Equal("result1", executedContext2.Response.Value);
            Assert.Equal("result1", executedContext3.Response.Value);
        }
Example #24
0
        private CacheProvider GetProvider(CacheAttribute cacheAttr)
        {
            CacheQueryAttribute cacheQueryAttr = cacheAttr as CacheQueryAttribute;
            if (cacheQueryAttr != null)
            {
                return new CacheQueryProvider(cacheQueryAttr.CacheKey);
            }

            CacheRefreshAttribute cacheRefreshAttr = cacheAttr as CacheRefreshAttribute;
            if (cacheRefreshAttr != null)
            {
                return new CacheRefreshProvider(cacheRefreshAttr.CacheKey);
            }
            return null;
        }
Example #25
0
        private void HandleAsyncReadMethod <TResult>(IInvocation invocation, CacheAttribute cacheAttribute)
        {
            //find cache attribute
            string refreshParamName;
            var    refreshCache = GetRefreshCacheValue(invocation, out refreshParamName);

            var arguments  = invocation.Arguments;
            var parameters = invocation.Method.GetParameters();
            var keyPattern = cacheAttribute.Key;

            var cacheKey = string.IsNullOrWhiteSpace(keyPattern) ?
                           GetDefaulTaskCacheKey(invocation.Method, refreshParamName, invocation.Arguments) : FormatWithParameters(keyPattern, parameters, arguments);

            var result = default(TResult);

            if (!refreshCache && TryGetCache(cacheKey, out result))
            {
                var tcs = new TaskCompletionSource <TResult>();
                tcs.SetResult(result);
                invocation.ReturnValue = tcs.Task;
                return;
            }

            var returnTcs = new TaskCompletionSource <TResult>();

            invocation.Proceed();
            var invocationReturn = invocation.ReturnValue as Task <TResult>;

            invocationReturn?.ContinueWith(t =>
            {
                if (!t.IsFaulted && t.Status == TaskStatus.RanToCompletion)
                {
                    AddCache(cacheKey, t.Result);
                    result = t.Result;
                }
                else
                {
                    //TODO: add log here
                    if (t.Exception?.InnerException != null)
                    {
                        throw t.Exception?.InnerException;
                    }
                }
                returnTcs.SetResult(result);
            });

            invocation.ReturnValue = returnTcs.Task;
        }
Example #26
0
        public void alter_chain_with_more_overridden_vary_by()
        {
            var att = new CacheAttribute();

            att.VaryBy = new Type[] { typeof(VaryByResource), typeof(VaryByThreadCulture) };

            var chain = new BehaviorChain();
            var call  = ActionCall.For <CacheAttributeTester>(x => x.alter_chain());

            chain.AddToEnd(call);

            att.Alter(call);

            chain.OfType <OutputCachingNode>().Single().VaryByPolicies()
            .ShouldHaveTheSameElementsAs(typeof(VaryByResource), typeof(VaryByThreadCulture));
        }
Example #27
0
        public void ETagUpdate()
        {
            CacheAttribute filter = new CacheAttribute {
                Update = true
            };
            Browser browser = new Browser();

            browser.MakeRequest(filter);
            Assert.IsTrue(browser.ETag != null);
            EntityTagHeaderValue eTag = browser.ETag;

            browser = new Browser(eTag);
            browser.MakeRequest(filter);
            Assert.AreNotEqual <EntityTagHeaderValue>(browser.ETag, eTag);
            Assert.IsTrue(browser.StatusCode == HttpStatusCode.OK);
        }
Example #28
0
        /// <summary>
        /// 执行,按实际结果返回
        /// </summary>
        /// <param name="letter">客户端递交的参数信息</param>
        /// <returns></returns>
        public static object Exec(Letter letter)
        {
            //1.创建对象,即$api.get("account/single")中的account
            object execObj = ExecuteMethod.CreateInstance(letter);
            //2.获取要执行的方法,即$api.get("account/single")中的single
            MethodInfo method = getMethod(execObj.GetType(), letter);

            //3#.验证方法的特性,一是验证Http动词,二是验证是否登录后操作,三是验证权限
            //----验证Http谓词访问限制
            HttpAttribute.Verify(letter.HTTP_METHOD, method);
            //LoginAttribute.Verify(method);
            //----范围控制,本机或局域网,或同域
            bool isRange = RangeAttribute.Verify(letter, method);
            //----验证是否需要登录
            LoginAttribute loginattr = LoginAttribute.Verify(method);


            //4.构建执行该方法所需要的参数
            object[] parameters = getInvokeParam(method, letter);
            //5.执行方法,返回结果
            object objResult = null;    //结果
            //只有get方式时,才使用缓存
            CacheAttribute cache = null;

            if (letter.HTTP_METHOD == "GET")
            {
                cache = CacheAttribute.GetAttr <CacheAttribute>(method);
            }
            if (cache != null)
            {
                objResult = CacheAttribute.GetResult(method, letter);
                if (objResult == null)
                {
                    objResult = method.Invoke(execObj, parameters);
                    CacheAttribute.Insert(cache.Expires, method, letter, objResult);
                }
            }
            else
            {
                objResult = method.Invoke(execObj, parameters);
            }
            //将执行结果写入日志
            LoginAttribute.LogWrite(loginattr, objResult);
            return(objResult);
        }
Example #29
0
        public void OutputCacheSimple()
        {
            ClearCache();

            CacheAttribute filter = new CacheAttribute {
                CacheOnServer = true
            };
            Browser browser = new Browser();

            browser.MakeRequest(filter);
            Assert.IsTrue(browser.StatusCode == HttpStatusCode.OK);
            Assert.IsTrue(browser.ControllerExecuted);
            Browser browser2 = new Browser();

            browser2.MakeRequest(filter);
            Assert.IsTrue(browser2.StatusCode == HttpStatusCode.OK);
            Assert.IsFalse(browser2.ControllerExecuted);
        }
Example #30
0
        public void WhenExecutingFilterThenCacheIsChecked()
        {
            // Arrange
            CacheAttribute filter  = this.CreateAttribute();
            SimpleCommand  command = new SimpleCommand {
                Property1 = 12, Property2 = "test"
            };
            CommandHandlerRequest    request    = new CommandHandlerRequest(this.config, command);
            CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler));
            CommandHandlerContext    context    = new CommandHandlerContext(request, descriptor);

            // Act
            filter.OnCommandExecuting(context);

            // Assert
            this.cache.Verify(c => c.Get(It.IsAny <string>(), It.IsAny <string>()), Times.Once());
            Assert.Null(context.Response);
        }
Example #31
0
        public IMethodInvocationResult Intercept(ISyncMethodInvocation methodInvocation)
        {
            IMethodInvocationResult result = null;

            CacheAttribute attribute = methodInvocation.InstanceMethodInfo.GetCustomAttribute <CacheAttribute>();

            if (attribute != null)
            {
                string key  = KeyBuilder.BuildCacheKey(attribute.CacheSetting, attribute.CacheName, methodInvocation.TargetInstance.ToString(), methodInvocation.InstanceMethodInfo.Name, attribute.PropertyName, methodInvocation.Arguments.ToArray());
                string area = KeyBuilder.BuildCacheKey(attribute.CacheSetting, attribute.CacheArea, methodInvocation.TargetInstance.ToString(), methodInvocation.InstanceMethodInfo.Name, attribute.PropertyName, methodInvocation.Arguments.ToArray());

                CachedItemDTO cachedItem = CacheManager.GetValue(area, key);

                object cachedValue = null;

                if (cachedItem != null)
                {
                    cachedValue = cachedItem.CacheValue;
                }

                if (cachedValue != null)
                {
                    MethodInfo methodInfo = methodInvocation.InstanceMethodInfo;
                    Type       typeFoo    = methodInfo.ReturnType;

                    var returnData = Convert.ChangeType(cachedValue, typeFoo);

                    return(methodInvocation.CreateResult(returnData));
                }
                else
                {
                    result = methodInvocation.InvokeNext();

                    CacheManager.AddValue(area, key, result.ReturnValue, attribute.TimeoutSeconds);

                    return(result);
                }
            }
            else
            {
                result = methodInvocation.InvokeNext();
                return(result);
            }
        }
Example #32
0
        /// <summary> Write a Cache XML Element from attributes in a member. </summary>
        public virtual void WriteCache(System.Xml.XmlWriter writer, System.Reflection.MemberInfo member, CacheAttribute attribute, BaseAttribute parentAttribute, System.Type mappedClass)
        {
            writer.WriteStartElement( "cache" );
            // Attribute: <usage>
            writer.WriteAttributeString("usage", attribute.Usage==CacheUsage.Unspecified ? DefaultHelper.Get_Cache_Usage_DefaultValue(member) : GetXmlEnumValue(typeof(CacheUsage), attribute.Usage));
            // Attribute: <region>
            if(attribute.Region != null)
            writer.WriteAttributeString("region", GetAttributeValue(attribute.Region, mappedClass));
            // Attribute: <include>
            if(attribute.Include != CacheInclude.Unspecified)
            writer.WriteAttributeString("include", GetXmlEnumValue(typeof(CacheInclude), attribute.Include));

            WriteUserDefinedContent(writer, member, null, attribute);

            writer.WriteEndElement();
        }
Example #33
0
 public override CacheAttribute[] GetAttributes(string cachecode)
 {
     Trace("Getting Attributes for " + cachecode);
     IDataReader rdr = ExecuteSQLQuery(String.Format(GET_ATTRIBUTES, cachecode));
     List<CacheAttribute> attrs = new List<CacheAttribute>();
     while (rdr.Read())
     {
         CacheAttribute attr = new CacheAttribute();
         attr.ID = rdr.GetString(0);
         string val = rdr.GetString(1);
         attr.Include = bool.Parse(val);
         attr.AttrValue = rdr.GetString(2);
         attrs.Add(attr);
     }
     return attrs.ToArray();
 }
Example #34
0
 public void RaiseExecutingTest()
 {
     var executorAttr = new CacheAttribute("group") as IExecutorAttribute;
     Assert.True(Assert.Throws<NotSupportedException>(() => executorAttr.RaiseExecuting(null, new Command1())).Message.EndsWith(":命令模型没有实现缓存接口。"));
     Assert.True(Assert.Throws<NotSupportedException>(() => executorAttr.RaiseExecuting(null, new Command2() { NullStrategy = true })).Message.EndsWith(":命令模型返回了无效的策略信息。"));
     Assert.True(Assert.Throws<NotSupportedException>(() => executorAttr.RaiseExecuting(null, new Command2() { NullStrategy = false })).Message.EndsWith(":命令模型返回了无效的策略信息。"));
 }
Example #35
0
 public override void AddAttribute(string parent, CacheAttribute attribute)
 {
     Trace("Adding attribute for " + parent);
     ExecuteSQLCommand(String.Format(ADD_ATTRIBUTE, parent, attribute.ID, attribute.Include.ToString(),
                                     attribute.AttrValue));
 }
Example #36
0
 public void RaiseExecutedTest()
 {
     var executorAttr = new CacheAttribute("group") as IExecutorAttribute;
     executorAttr.RaiseExecuted(null, null, new Exception());
 }
Example #37
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // read configuration settings
            cache_enabled = ConfigurationManager.AppSettings["cache_enabled"].ToString() == "true";

            // check custom attributes - if any
            cache_attribute = (CacheAttribute)filterContext.ActionDescriptor.GetCustomAttributes(typeof(CacheAttribute), false).FirstOrDefault();
            omit_database = filterContext.ActionDescriptor.GetCustomAttributes(typeof(OmitDatabaseAttribute), false).FirstOrDefault() != null;

            // if the attribute cache is present and the cache is enabled in the parameter in the web.config file
            if (cache_enabled && cache_attribute != null)
            {

                cache_ID = filterContext.ActionDescriptor.ActionName + "_" + string.Join("_", filterContext.ActionParameters.Values);
                cache = new MongoCache();

                String cached = cache.Get(cache_ID);

                // if the item is already in the "cache"
                if (cached != null)
                {
                    var result = new ContentResult();
                    result.ContentType = "application/json";
                    result.Content = cached;

                    filterContext.Result = result;
                    return;
                }

            }

            // initiate the database only if it is needed
            if (!omit_database)
            {
                database = new Database(ConfigurationManager.AppSettings["connectionString"].ToString());
            }

            base.OnActionExecuting(filterContext);
        }
Example #38
0
 public override Dictionary<string, List<CacheAttribute>> GetAttributesMulti(string[] cachecodes)
 {
     Trace("Getting Attributes Multi");
     IDataReader rdr = ExecuteSQLQuery(String.Format(GET_ATTRIBUTES_MULTI, ArrayToSQL(cachecodes)));
     Dictionary<string, List<CacheAttribute>> attrs = new Dictionary<string, List<CacheAttribute>>();
     while (rdr.Read())
     {
         CacheAttribute attr = new CacheAttribute();
         attr.ID = rdr.GetString(0);
         string val = rdr.GetString(1);
         attr.Include = bool.Parse(val);
         attr.AttrValue = rdr.GetString(2);
         string code = rdr.GetString(3);
         if (!attrs.ContainsKey(code))
             attrs.Add(code, new List<CacheAttribute>());
         attrs[code].Add(attr);
     }
     return attrs;
 }