public async Task OnMethodExecutingAsync_should_wait_on_async_void_TaskResult()
        {
            var wait = new ManualResetEvent(false);
            var invocation = Substitute.For<_IInvocation>();
            invocation.When(x => x.Proceed()).Do(c => wait.Set());
            Task task = null;
            invocation.ReturnValue.Returns(c =>
            {
                if (task == null)
                {
                    task = Task.Factory.StartNew(async () =>
                    {
                        await Task.Delay(100);
                        Assert.IsTrue(wait.WaitOne(2000));
                    });
                }
                return task;
            });

            var context = new MethodExecutingContext
            {
                Invocation = invocation,
                InvocationContext = new Dictionary<string, object>(),
            };

            var filter = new InvocationAttribute(invocation);
            await filter.OnMethodExecutingAsync(context);

            // Assert
            var taskResult = invocation.ReturnValue as Task;
            Assert.IsNull(context.Result);
            Assert.IsNotNull(taskResult);
            Assert.AreEqual(TaskStatus.RanToCompletion, taskResult.Status);
        }
 internal MethodExecutedContext(MethodExecutingContext executingContext)
 {
     Invocation = executingContext.Invocation;
     MethodInfo = executingContext.MethodInfo;
     InvocationContext = new Dictionary<string, object>(executingContext.InvocationContext);
     Result = executingContext.Result;
 }
        public void Should_attempt_to_refresh_cache_when_cache_is_stale()
        {
            // Arrange
            Global.Init();
            var wait        = new AutoResetEvent(false);
            var userService = Substitute.For <IUserService>();

            userService.When(x => x.GetById(Arg.Any <Guid>())).Do(c => { wait.Set(); });
            var activator = Substitute.For <IServiceActivator>();

            activator.BeginScope().Returns(activator);
            activator.CreateInstance(Arg.Any <Type>()).Returns(userService);

            Global.ServiceActivator = activator;
            var cacheStore = Substitute.For <ICacheStore>();

            cacheStore.StoreId.Returns(10);
            cacheStore.Get(Arg.Any <string>()).Returns(c => new CacheItem
            {
                StaleWhileRevalidate = 5,
                StoreId     = 10,
                MaxAge      = 5,
                CreatedTime = DateTime.UtcNow.AddSeconds(-6),
                Key         = c.Arg <string>(),
                Data        = "Cache content"
            });
            Global.CacheStoreProvider.RegisterStore(cacheStore);
            var att = new OutputCacheAttribute {
                CacheStoreId = cacheStore.StoreId, Duration = 5, StaleWhileRevalidate = 5
            };


            var invocation = Substitute.For <_IInvocation>();

            invocation.Method.Returns(typeof(IUserService).GetMethod(nameof(IUserService.GetById)));
            invocation.Arguments.Returns(new object[] { Guid.NewGuid() });

            var context = new Dictionary <string, object>
            {
                [Global.__flatwhite_outputcache_attribute] = new OutputCacheAttribute
                {
                    CacheStoreId = 100
                }
            };
            var executingContext = new MethodExecutingContext
            {
                Invocation        = invocation,
                InvocationContext = context,
                MethodInfo        = invocation.Method
            };

            // Action
            att.OnMethodExecuting(executingContext);
            Assert.IsTrue(wait.WaitOne(2000));
        }
        public void Should_attempt_to_refresh_cache_when_cache_is_stale()
        {
            // Arrange
            Global.Init();
            var wait = new AutoResetEvent(false);
            var userService = Substitute.For<IUserService>();
            userService.When(x => x.GetById(Arg.Any<Guid>())).Do(c => { wait.Set(); });
            var activator = Substitute.For<IServiceActivator>();
            activator.BeginScope().Returns(activator);
            activator.CreateInstance(Arg.Any<Type>()).Returns(userService);

            Global.ServiceActivator = activator;
            var cacheStore = Substitute.For<ICacheStore>();
            cacheStore.StoreId.Returns(10);
            cacheStore.Get(Arg.Any<string>()).Returns(c => new CacheItem
            {
                StaleWhileRevalidate = 5,
                StoreId = 10,
                MaxAge = 5,
                CreatedTime = DateTime.UtcNow.AddSeconds(-6),
                Key = c.Arg<string>(),
                Data = "Cache content"
            });
            Global.CacheStoreProvider.RegisterStore(cacheStore);
            var att = new OutputCacheAttribute {CacheStoreId = cacheStore.StoreId, Duration = 5, StaleWhileRevalidate = 5};

            
            var invocation = Substitute.For<_IInvocation>();
            invocation.Method.Returns(typeof (IUserService).GetMethod(nameof(IUserService.GetById)));
            invocation.Arguments.Returns(new object[] {Guid.NewGuid()});

            var context = new Dictionary<string, object>
            {
                [Global.__flatwhite_outputcache_attribute] = new OutputCacheAttribute
                {
                    CacheStoreId = 100
                }
            };
            var executingContext = new MethodExecutingContext
            {
                Invocation =  invocation,
                InvocationContext = context,
                MethodInfo = invocation.Method
            };

            // Action
            att.OnMethodExecuting(executingContext);
            Assert.IsTrue(wait.WaitOne(2000));
        }
        public void OnMethodExecuting_should_proceed_the_invocation_and_set_result()
        {
            var invocation = Substitute.For<_IInvocation>();
            invocation.ReturnValue.Returns(10);
            var context = new MethodExecutingContext
            {
                Invocation = invocation,
                InvocationContext = new Dictionary<string, object>(),
            };

            var filter = new InvocationAttribute(invocation, null);
            filter.OnMethodExecuting(context);

            // Assert
            Assert.AreEqual(10, context.Result);
            invocation.Received(1).Proceed();
        }
Exemple #6
0
        public void OnMethodExecuting_should_proceed_the_invocation_and_set_result()
        {
            var invocation = Substitute.For <_IInvocation>();

            invocation.ReturnValue.Returns(10);
            var context = new MethodExecutingContext
            {
                Invocation        = invocation,
                InvocationContext = new Dictionary <string, object>(),
            };

            var filter = new InvocationAttribute(invocation, null);

            filter.OnMethodExecuting(context);

            // Assert
            Assert.AreEqual(10, context.Result);
            invocation.Received(1).Proceed();
        }
        public override async Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
        {
            _invocation.Proceed();

            if (_invocation.ReturnValue is Task taskResult)
            {
                if (_taskGenericReturnType != null)
                {
                    actionContext.Result = await taskResult.TryGetTaskResult();
                }
                else
                {
                    await taskResult;
                }
            }
            else
            {
                actionContext.Result = _invocation.ReturnValue;
            }
        }
        public async Task OnMethodExecutingAsync_should_proceed_the_invocation_and_set_result()
        {
            var wait = new ManualResetEvent(false);
            var invocation = Substitute.For<_IInvocation>();
            invocation.When(x => x.Proceed()).Do(c => wait.Set());
            invocation.ReturnValue.Returns(c => Task<int>.Factory.StartNew(() =>
            {
                Assert.IsTrue(wait.WaitOne(2000));
                return 10;
            }));

            var context = new MethodExecutingContext
            {
                Invocation = invocation,
                InvocationContext = new Dictionary<string, object>(),
            };

            var filter = new InvocationAttribute(invocation, typeof(int));
            await filter.OnMethodExecutingAsync(context);

            // Assert
            Assert.AreEqual(10, context.Result);
        }
Exemple #9
0
        public async Task OnMethodExecutingAsync_should_wait_on_async_void_TaskResult()
        {
            var wait       = new ManualResetEvent(false);
            var invocation = Substitute.For <_IInvocation>();

            invocation.When(x => x.Proceed()).Do(c => wait.Set());
            Task task = null;

            invocation.ReturnValue.Returns(c =>
            {
                if (task == null)
                {
                    task = Task.Factory.StartNew(async() =>
                    {
                        await Task.Delay(100);
                        Assert.IsTrue(wait.WaitOne(2000));
                    });
                }
                return(task);
            });

            var context = new MethodExecutingContext
            {
                Invocation        = invocation,
                InvocationContext = new Dictionary <string, object>(),
            };

            var filter = new InvocationAttribute(invocation);
            await filter.OnMethodExecutingAsync(context);

            // Assert
            var taskResult = invocation.ReturnValue as Task;

            Assert.IsNull(context.Result);
            Assert.IsNotNull(taskResult);
            Assert.AreEqual(TaskStatus.RanToCompletion, taskResult.Status);
        }
Exemple #10
0
        public async Task OnMethodExecutingAsync_should_proceed_and_set_result_if_the_invocation_result_is_not_Task()
        {
            var wait       = new ManualResetEvent(false);
            var invocation = Substitute.For <_IInvocation>();

            invocation.When(x => x.Proceed()).Do(c => wait.Set());
            invocation.ReturnValue.Returns(c =>
            {
                Assert.IsTrue(wait.WaitOne(2000));
                return(10);
            });

            var context = new MethodExecutingContext
            {
                Invocation        = invocation,
                InvocationContext = new Dictionary <string, object>(),
            };

            var filter = new InvocationAttribute(invocation, typeof(int));
            await filter.OnMethodExecutingAsync(context);

            // Assert
            Assert.AreEqual(10, context.Result);
        }
 public override Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
 {
     //Console.WriteLine($"{DateTime.Now} {nameof(TestMethod2FilterAttribute)} OnMethodExecutingAsync");
     return(TaskHelpers.DefaultCompleted);
 }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
     //Console.WriteLine($"{DateTime.Now} {nameof(TestMethod2FilterAttribute)} OnMethodExecuting");
 }
Exemple #13
0
        /// <summary>
        /// Intercept the invocation
        /// </summary>
        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            var methodParameterTypes = targetMethod.GetParameters().Select(p => p.ParameterType).ToArray();
            var classMethodInfo      = _decorated != null
                        ? _decorated.GetType().GetMethod(targetMethod.Name, methodParameterTypes)
                                : targetMethod;

            var invocation = new Invocation
            {
                Arguments              = args,
                GenericArguments       = targetMethod.IsGenericMethod ? targetMethod.GetGenericArguments() : new Type[0],
                InvocationTarget       = _decorated,
                Method                 = targetMethod,
                Proxy                  = this,
                MethodInvocationTarget = classMethodInfo,
                TargetType             = _decorated != null?_decorated.GetType() : typeof(T)
            };

            var methodExecutingContext = new MethodExecutingContext
            {
                InvocationContext = _contextProvider.GetContext(),
                MethodInfo        = targetMethod,
                Invocation        = invocation
            };

            var attributes = GetInvocationMethodFilterAttributes(invocation, methodExecutingContext.InvocationContext);

            if (attributes.Any(a => a is NoInterceptAttribute))
            {
                invocation.Proceed();
                return(invocation.ReturnValue);
            }

            var methodFilterAttributes    = attributes.OfType <MethodFilterAttribute>().OrderBy(x => x.Order).ToList();
            var exceptionFilterAttributes = attributes.OfType <ExceptionFilterAttribute>().ToList();

            var isAsync = typeof(Task).IsAssignableFrom(invocation.Method.ReturnType);

            if (isAsync)
            {
                if (invocation.Method.ReturnType.IsGenericType && invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    var taskResultType = invocation.Method.ReturnType.GetGenericArguments()[0];
                    var mInfo          = HandleAsyncWithTypeMethod.MakeGenericMethod(taskResultType);
                    if (_decorated != null)
                    {
                        methodFilterAttributes.Add(new InvocationAttribute(invocation, taskResultType));
                    }
                    invocation.ReturnValue = mInfo.Invoke(this, new object[] { methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext });
                }
                else
                {
                    if (_decorated != null)
                    {
                        methodFilterAttributes.Add(new InvocationAttribute(invocation));
                    }
                    invocation.ReturnValue = HandleAsync(methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext);
                }
            }
            else
            {
                if (_decorated != null)
                {
                    methodFilterAttributes.Add(new InvocationAttribute(invocation));
                }
                HandleSync(methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext);
            }
            return(invocation.ReturnValue);
        }
Exemple #14
0
        private async Task HandleAsync(IReadOnlyList <MethodFilterAttribute> filterAttributes, IReadOnlyList <ExceptionFilterAttribute> exceptionFilterAttributes, MethodExecutingContext methodExecutingContext)
        {
            foreach (var f in filterAttributes)
            {
                try
                {
                    if (methodExecutingContext.Result == null)
                    {
                        await f.OnMethodExecutingAsync(methodExecutingContext).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    var exContext = new MethodExceptionContext(ex, methodExecutingContext);
                    await HandleExceptionAsync(exceptionFilterAttributes, exContext);

                    if (!exContext.Handled)
                    {
                        throw;
                    }
                }
            }

            var reversedFilterAttributes = filterAttributes.Reverse();
            var methodExecutedContext    = new MethodExecutedContext(methodExecutingContext);

            foreach (var f in reversedFilterAttributes)
            {
                try
                {
                    await f.OnMethodExecutedAsync(methodExecutedContext).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    var exContext = new MethodExceptionContext(ex, methodExecutedContext);
                    await HandleExceptionAsync(exceptionFilterAttributes, exContext);

                    if (!exContext.Handled)
                    {
                        throw;
                    }
                }
            }
        }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
 }
Exemple #16
0
 public virtual Task OnMethodExecutingAsync(MethodExecutingContext methodExecutingContext)
 {
     OnMethodExecuting(methodExecutingContext);
     return(Task.CompletedTask);
 }
 public override Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
 {
     return TaskHelpers.DefaultCompleted;
 }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
 }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
     _invocation.Proceed();
     methodExecutingContext.Result = _invocation.ReturnValue;
 }
 public override Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
 {
     return(TaskHelpers.DefaultCompleted);
 }
 /// <summary>
 /// Called before a service method is executed.
 /// </summary>
 /// <param name="serviceContext">The service context.</param>
 /// <param name="behaviorContext">The "method executing" behavior context.</param>
 /// <returns>A service method action.</returns>
 public virtual BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
 {
     return BehaviorMethodAction.Execute;
 }
Exemple #22
0
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
     methodExecutingContext.InvocationContext[$"{nameof(FilterAttributeOnClassMethod)}.{nameof(OnMethodExecutedAsync)}"] = DateTime.UtcNow;
 }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
     throw new Exception($"{nameof(BadMethodFilterAttribute)}.{nameof(OnMethodExecuting)}");
 }
 public override void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
     //Console.WriteLine($"{DateTime.Now} {nameof(TestMethod2FilterAttribute)} OnMethodExecuting");
 }
Exemple #25
0
 public virtual void OnMethodExecuting(MethodExecutingContext methodExecutingContext)
 {
 }
Exemple #26
0
 public override Task OnMethodExecutingAsync(MethodExecutingContext methodExecutingContext)
 {
     methodExecutingContext.InvocationContext[$"{nameof(FilterAttributeOnClassMethod)}.{nameof(OnMethodExecutingAsync)}"] = DateTime.UtcNow;
     return(Task.CompletedTask);
 }
 public override Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
 {
     //Console.WriteLine($"{DateTime.Now} {nameof(TestMethod2FilterAttribute)} OnMethodExecutingAsync");
     return TaskHelpers.DefaultCompleted;
 }
 public override Task OnMethodExecutingAsync(MethodExecutingContext actionContext)
 {
     throw new Exception($"{nameof(BadMethodFilterAttribute)}.{nameof(OnMethodExecutingAsync)}");
 }
Exemple #29
0
        private void HandleSync(IReadOnlyList <MethodFilterAttribute> filterAttributes, IReadOnlyList <ExceptionFilterAttribute> exceptionFilterAttributes, MethodExecutingContext methodExecutingContext)
        {
            foreach (var f in filterAttributes)
            {
                try
                {
                    if (methodExecutingContext.Result == null)
                    {
                        f.OnMethodExecuting(methodExecutingContext);
                    }
                }
                catch (Exception ex)
                {
                    var exContext = new MethodExceptionContext(ex, methodExecutingContext);
                    HandleException(exceptionFilterAttributes, exContext);
                    if (!exContext.Handled)
                    {
                        throw;
                    }
                }
            }

            var reversedFilterAttributes = filterAttributes.Reverse();
            var methodExecutedContext    = new MethodExecutedContext(methodExecutingContext);

            foreach (var f in reversedFilterAttributes)
            {
                try
                {
                    f.OnMethodExecuted(methodExecutedContext);
                }
                catch (Exception ex)
                {
                    var exContext = new MethodExceptionContext(ex, methodExecutedContext);
                    HandleException(exceptionFilterAttributes, exContext);
                    if (!exContext.Handled)
                    {
                        throw;
                    }
                }
            }
        }