示例#1
0
文件: MyTest.cs 项目: juszhc/CodeArts
        public IEmit TestClas()
        {
            var binder = new InvokeBinder(instance, typeof(MyTest).GetMethod("TestClas"), new object[0]);

            interceptor.Intercept(binder);

            var returnValue = binder.ReturnValue;

            return((IEmit)returnValue);
        }
示例#2
0
    public override int CachedMethod(int p1, int p2)
    {
        int returnValue = 0;

        if (_methodInfo == null)
        {
            _methodInfo = new CallMethodInfo((MethodInfo)MethodBase.GetCurrentMethod());
        }

        InterceptCallInfo info = new InterceptCallInfo();

        info.Object             = this;
        info.CallMethodInfo     = _methodInfo;
        info.ParameterValues[0] = p1;
        info.ParameterValues[1] = p2;
        info.ReturnValue        = returnValue;
        info.InterceptResult    = InterceptResult.Continue;
        info.InterceptType      = InterceptType.BeforeCall;

        if (_interceptor == null)
        {
            _interceptor = new CacheAspect();
            _interceptor.Init(_methodInfo, "MaxCacheTime=500;IsWeak=False");
        }

        // 'BeforeCall' step checks if the method is cached.
        // If it is and the cache is not expired, the Intercept method populates
        // return value and output parameters with the cached values and
        // sets info.InterceptResult to InterceptResult.Return.
        // See the [link][file]Aspects/CacheAspect.cs[/file]CacheAspect.BeforeCall[/link] method for details.
        //
        _interceptor.Intercept(info);

        returnValue = (int)info.ReturnValue;

        if (info.InterceptResult != InterceptResult.Return)
        {
            // If the method call is not cached, target method is called.
            //
            returnValue = base.CachedMethod(p1, p2);

            info.ReturnValue     = returnValue;
            info.InterceptResult = InterceptResult.Continue;
            info.InterceptType   = InterceptType.AfterCall;

            // 'AfterCall' step stores parameters and return values in the cache.
            // See the [link][file]Aspects/CacheAspect.cs[/file]CacheAspect.AfterCall[/link] method for details.
            //
            _interceptor.Intercept(info);

            returnValue = (int)info.ReturnValue;
        }

        return(returnValue);
    }
示例#3
0
 public void Intercept(IInvocation invocation)
 {
     invocation.Proceed();
     if (IsDefaultValueAResultOf(invocation) && !_methodsNotToOverride.Contains(invocation.Method))
     {
         _interfaceInterceptor.Intercept(invocation);
     }
     else if (_methodsWithForcedOverride.Contains(invocation.Method))
     {
         _interfaceInterceptor.Intercept(invocation);
     }
 }
示例#4
0
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <typeparam name="T">返回类型。</typeparam>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用结果。</returns>
        protected async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId)
        {
            object result  = default(T);
            var    command = await _commandProvider.GetCommand(serviceId);

            RemoteInvokeResultMessage message;

            if (!command.RequestCacheEnabled)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey);

                if (message == null)
                {
                    var invoker = _serviceProvider.GetInstances <IClusterInvoker>(command.Strategy.ToString());
                    return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey));
                }
            }
            else
            {
                var invocation = GetInvocation(parameters, serviceId, typeof(T));
                await _interceptor.Intercept(invocation);

                message = invocation.ReturnValue is RemoteInvokeResultMessage
                    ? invocation.ReturnValue as RemoteInvokeResultMessage : null;
                result = invocation.ReturnValue;
            }

            if (message != null)
            {
                result = _typeConvertibleService.Convert(message.Result, typeof(T));
            }
            return((T)result);
        }
 public static void UseInterceptorFor <T>(
     this IKernel kernel,
     Expression <Action <T> > methodExpr,
     IInterceptor interceptor)
 {
     kernel.InterceptReplace <T>(methodExpr, inv => interceptor.Intercept(inv));
 }
示例#6
0
        private async Task <Tuple <RemoteInvokeResultMessage, object> > Intercept(IInterceptor interceptor, IInvocation invocation)
        {
            await interceptor.Intercept(invocation);

            var message = invocation.ReturnValue is RemoteInvokeResultMessage
             ? invocation.ReturnValue as RemoteInvokeResultMessage : null;

            return(new Tuple <RemoteInvokeResultMessage, object>(message, invocation.ReturnValue));
        }
示例#7
0
        public object Intercept(IInvocationInfo info)
        {
            _callCounter.Increment(info);

            var returnValue = _methodReplacement.Intercept(info);

            _callCounter.Decrement(info);

            return(returnValue);
        }
        public void ShouldReturnInterfaceProxy()
        {
            var          dummyObjectFactory = new DummyObject.Factory();
            IDummyObject dummyObject        = dummyObjectFactory.Create();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo(() => dummyObjectFactory.Create()));
            mockInvocation.ReturnValue.Returns(dummyObject);

            Assert.AreEqual(dummyObject, mockInvocation.ReturnValue);
            classUnderTest.Intercept(mockInvocation);
            Assert.AreNotEqual(dummyObject, mockInvocation.ReturnValue);

            IDummyObject proxy = mockInvocation.ReturnValue as IDummyObject;

            Assert.NotNull(proxy);
            Assert.AreEqual(0, aspect.CallCount);
            proxy.SetValue(0);
            Assert.AreEqual(1, aspect.CallCount);
        }
        public VariableData Do(ReferenceData target, string operation, Dictionary <string, ParameterValueData> parameters)
        {
            var context = NewContext(target, operation, parameters);
            var service = GetService(context);

            return(@do.Intercept(context,
                                 () => service.Intercept(context,
                                                         () => real.Do(context.TargetReference, context.OperationName, context.ParameterValues)
                                                         )
                                 ) as VariableData);
        }
示例#10
0
 public void Intercept(IInvocation invocation)
 {
     if (_policy.ShouldIntercept(invocation))
     {
         _interceptor.Intercept(invocation);
     }
     else
     {
         _elseInterceptor.Intercept(invocation);
     }
 }
示例#11
0
        public virtual void Intercept(IInvocation invocation)
        {
            if (this.Type != null)
            {
                if (_interceptor == null)
                {
                    _interceptor = Activator.CreateInstance(this.Type) as IInterceptor;
                }

                _interceptor.Intercept(invocation);
            }
        }
示例#12
0
 /// <inheritdoc />
 public void Proceed()
 {
     if (interceptorIndex == interceptorStub.Interceptors.Length)
     {
         InvokeMethodOnTarget();
     }
     else
     {
         IInterceptor interceptor = interceptorStub.Interceptors[interceptorIndex++];
         interceptor.Intercept(this);
     }
 }
示例#13
0
        public void ShouldSendEventInfoToLogger()
        {
            var mockInvocation = Substitute.For <IInvocation>();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo <DummyObject>(x => x.SetValue(1)));
            mockInvocation.TargetType.Returns(typeof(DummyObject));

            _classUnderTest.Intercept(mockInvocation);
            _mockTraceLogger.Received().TraceEvent("SetValue", EventType.Sync, typeof(DummyObject),
                                                   Arg.Is <long>(1), Arg.Is <long>(1),
                                                   Arg.Any <int>());
        }
        public void TargetSelfIsSetToProxy()
        {
            var factory   = new Factory();
            var targetObj = factory.Create();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo(() => factory.Create()));
            mockInvocation.ReturnValue.Returns(targetObj);

            Assert.AreEqual(targetObj, mockInvocation.ReturnValue);
            classUnderTest.Intercept(mockInvocation);
            Assert.AreNotEqual(targetObj, mockInvocation.ReturnValue);
            Assert.AreSame(((TargetObjImpl)targetObj).Self, mockInvocation.ReturnValue);
        }
示例#15
0
        /// <summary>
        /// Calls the next interceptor. If no more interceptors are available, call the invoked method.
        /// </summary>
        public void Proceed()
        {
            if (this._interceptorIndex < this.Interceptors.Count())
            {
                IInterceptor interceptor = this.Interceptors.ElementAt(this._interceptorIndex);

                this._interceptorIndex++;

                interceptor.Intercept(this);
            }
            else
            {
                this.ReturnValue = this.MethodInvocation(this.InvokedMethod, this.InvokedInstance, this.Arguments);
            }
        }
示例#16
0
            public void Train(byte[] grayScaleHW, int width, int height, int stride)
            {
                if (IsOperational())
                {
                    throw new InvalidDataException("Model is operational.");
                }
                _amountOfTrainingFramesLeft--;

                _interceptor.Intercept(_amountOfTrainingFrames - _amountOfTrainingFramesLeft, _amountOfTrainingFrames);

                _stride = stride;
                _width  = width;
                _height = height;

                _trainingDataNHW[_amountOfTrainingFramesLeft] = grayScaleHW;

                if (_minIntensity == null)
                {
                    _minIntensity = new byte[grayScaleHW.Length];
                }
                if (_maxIntensity == null)
                {
                    _maxIntensity = new byte[grayScaleHW.Length];
                }
                if (_maxPerFrameDifference == null)
                {
                    _maxPerFrameDifference = new byte[grayScaleHW.Length];
                }

                if (_averageBackground == null)
                {
                    _averageBackground = new byte[grayScaleHW.Length];
                }

                if (_energyBackground == null)
                {
                    _energyBackground = new double[grayScaleHW.Length];
                }

                if (_amountOfTrainingFramesLeft == 0)
                {
                    CalculateInitialBackgroundModelState();
                }
            }
示例#17
0
        public string Process(Bitmap bitmap)
        {
            if (_differenceFilter.OverlayImage == null)
            {
                _differenceFilter.OverlayImage = (Bitmap)bitmap.Clone();
                return(null);
            }
            using (var difference = _differenceFilter.Apply(bitmap))
            {
                _interceptor.Intercept(DifferenceImage, ImageHelper.ToBytes(difference));

                if (_differenceFilter.WhitePixelsCount > _reportDifference)
                {
                    return(DateTime.Now.ToString("g") + " Frame difference is " + _differenceFilter.WhitePixelsCount + " pixels, filter threthhold " + _threshold);
                }
            }

            return(null);
        }
示例#18
0
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <typeparam name="T">返回类型。</typeparam>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用结果。</returns>
        protected async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId)
        {
            object result  = default(T);
            var    command = await _commandProvider.GetCommand(serviceId);

            RemoteInvokeResultMessage message;
            var decodeJOject = typeof(T) == UtilityType.ObjectType;

            if (!command.RequestCacheEnabled || decodeJOject)
            {
                var v = typeof(T).FullName;
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message == null)
                {
                    if (command.FallBackName != null && _serviceProvider.IsRegistered <IFallbackInvoker>(command.FallBackName) && command.Strategy == StrategyType.FallBack)
                    {
                        var invoker = _serviceProvider.GetInstances <IFallbackInvoker>(command.FallBackName);
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey));
                    }
                    else
                    {
                        var invoker = _serviceProvider.GetInstances <IClusterInvoker>(command.Strategy.ToString());
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey, typeof(T) == UtilityType.ObjectType));
                    }
                }
            }
            else
            {
                var invocation = GetInvocation(parameters, serviceId, typeof(T));
                await _interceptor.Intercept(invocation);

                message = invocation.ReturnValue is RemoteInvokeResultMessage
                    ? invocation.ReturnValue as RemoteInvokeResultMessage : null;
                result = invocation.ReturnValue;
            }

            if (message != null)
            {
                result = _typeConvertibleService.Convert(message.Result, typeof(T));
            }
            return((T)result);
        }
示例#19
0
        public override object Intercept(IInvocationInfo info)
        {
            // Instead of using the proxy as the target,
            // modify the InvocationInfo to show the actual target
            var proxyType = _proxyFactory.CreateProxyType(typeof(IInvocationInfo), new Type[0]);
            var infoProxy = Activator.CreateInstance(proxyType) as IProxy;

            if (infoProxy == null)
            {
                return(base.Intercept(info));
            }

            var modifiedInfo = (IInvocationInfo)infoProxy;

            // Replace the proxy target with the actual target
            var infoInterceptor = new InvocationInfoInterceptor(info, _getActualTarget, MethodInvoker);

            infoProxy.Interceptor = infoInterceptor;

            return(_interceptor.Intercept(modifiedInfo));
        }
示例#20
0
        public override IMessage Invoke(IMessage msg)
        {
            var mcm = msg as IMethodCallMessage;

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

            if (IsEqualsCall(mcm))
            {
                return(ReturnValue(HandleEquals(mcm), mcm));
            }

            if (IsGetHashCodeCall(mcm))
            {
                return(ReturnValue(GetHashCode(), mcm));
            }

            if (IsGetTypeCall(mcm))
            {
                return(ReturnValue(GetProxiedType(), mcm));
            }

            if (IsToStringCall(mcm))
            {
                var type     = GetProxiedType();
                var hashCode = GetHashCode();
                var value    = string.Format("RemotingMock_{0}<{1}>", hashCode, type.Name);

                return(ReturnValue(value, mcm));
            }

            var invocation = new RemotingInvocation(this, mcm);

            interceptor.Intercept(invocation);

            return(ReturnValue(invocation.ReturnValue, invocation.Arguments, mcm));
        }
示例#21
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage mcm = msg as IMethodCallMessage;

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

            if (IsEqualsMethod(mcm))
            {
                return(ReturnValue(HandleEquals(mcm), mcm));
            }

            if (IsGetHashCodeMethod(mcm))
            {
                return(ReturnValue(GetHashCode(), mcm));
            }

            if (IsGetTypeMethod(mcm))
            {
                return(ReturnValue(GetProxiedType(), mcm));
            }

            if (IsToStringMethod(mcm))
            {
                string retVal = String.Format("RemotingMock_{1}<{0}>", this.GetProxiedType().Name, this.GetHashCode());
                return(ReturnValue(retVal, mcm));
            }

            RemotingInvocation invocation = new RemotingInvocation(this, mcm);

            _interceptor.Intercept(invocation);

            return(ReturnValue(invocation.ReturnValue, invocation.Arguments, mcm));
        }
示例#22
0
        public string Process(Bitmap bitmap)
        {
            // When video device initializes it adapts to
            // background for some frames.
            if (_skipStartingFrames > 0)
            {
                _skipStartingFrames--;
                return(null);
            }

            using (var grayScaleImage = GrayScaleImageHelper.ToGrayScale(bitmap))
            {
                if (_grayScaleFrameTMinus1 == null ||
                    _grayScaleBackground == null)
                {
                    _grayScaleFrameTMinus1 = (Bitmap)grayScaleImage.Clone();
                    GrayScaleImageHelper.CalculateMeanAndVarianceM9(
                        _grayScaleFrameTMinus1,
                        out _imageTMinus1MeanWH,
                        out _imageTMinus1VarianceWH);
                    _grayScaleBackground = (Bitmap)grayScaleImage.Clone();
                    return(null);
                }

                var        bounds      = new Rectangle(0, 0, grayScaleImage.Width, grayScaleImage.Height);
                BitmapData bitmapData  = grayScaleImage.LockBits(bounds, ImageLockMode.ReadOnly, grayScaleImage.PixelFormat);
                var        grayScaleHW = new byte[grayScaleImage.Height * bitmapData.Stride];
                Marshal.Copy(bitmapData.Scan0, grayScaleHW, 0, grayScaleImage.Height * bitmapData.Stride);

                byte[,] imageTMean;
                byte[,] imageTVariance;
                byte[,] temporalImageAnalysisResultHW;
                byte[,] motionWH;
                bool motionPresents;
                using (var temporalImageAnalysisResult = GetRadiometricSimmilarity(
                           grayScaleImage.Width,
                           grayScaleImage.Height,
                           bitmapData.Stride,
                           grayScaleHW,
                           out temporalImageAnalysisResultHW,
                           out imageTMean,
                           out imageTVariance))
                {
                    _interceptor.Intercept(RadiometricSimmilarity, temporalImageAnalysisResult);

                    UpdateBackgroundOrForeground(
                        temporalImageAnalysisResultHW,
                        grayScaleImage.Width,
                        grayScaleImage.Height,
                        bitmapData.Stride,
                        grayScaleHW,
                        out motionPresents,
                        out motionWH);
                }

                _imageTMinus1MeanWH     = imageTMean;
                _imageTMinus1VarianceWH = imageTVariance;
                _grayScaleFrameTMinus1  = (Bitmap)grayScaleImage.Clone();
                grayScaleImage.UnlockBits(bitmapData);

                _interceptor.Intercept(DifferenceImage, GrayScaleImageHelper.FromWH(motionWH));

                if (motionPresents)
                {
                    return("Movement detected!");
                }
            }
            return(null);
        }
示例#23
0
        /// <summary>
        /// Intercepts the specified invocation.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="invocation"/> is <c>null</c>.</exception>
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            Argument.IsNotNull("invocation", invocation);

            invocation.ReturnValue = _interceptor.Intercept(new InvocationAdapter(invocation, _target));
        }
示例#24
0
 protected override object Intercept(IInterceptor <Context> testing) => testing.Intercept(context, invocation);
示例#25
0
 public void Intercept(IInvocation invocation) => _self.Intercept(invocation);
        public string Process(Bitmap bitmap)
        {
            // When video device initializes it adapts to
            // background for some frames.
            if (_skipStartingFrames > 0)
            {
                _skipStartingFrames--;
                return(null);
            }

            using (var grayScaleImage = GrayScaleImageHelper.ToGrayScale(bitmap))
            {
                if (_previous == null)
                {
                    byte[,] imageTMinus1MeanWH;
                    byte[,] imageTMinus1VarianceWH;
                    GrayScaleImageHelper.CalculateMeanAndVarianceM9(
                        grayScaleImage,
                        out imageTMinus1MeanWH,
                        out imageTMinus1VarianceWH);

                    _previous = new RadiometricSimilarityImage(
                        grayScaleImage,
                        imageTMinus1MeanWH,
                        imageTMinus1VarianceWH
                        );

                    _grayScaleBackground = (Bitmap)grayScaleImage.Clone();
                    return(null);
                }

                var        bounds      = new Rectangle(0, 0, grayScaleImage.Width, grayScaleImage.Height);
                BitmapData bitmapData  = grayScaleImage.LockBits(bounds, ImageLockMode.ReadOnly, grayScaleImage.PixelFormat);
                var        grayScaleHW = new byte[grayScaleImage.Height * bitmapData.Stride];
                Marshal.Copy(bitmapData.Scan0, grayScaleHW, 0, grayScaleImage.Height * bitmapData.Stride);
                grayScaleImage.UnlockBits(bitmapData);

                byte[,] imageTMean;
                byte[,] imageTVariance;
                byte[,] motionWH;
                bool motionPresents;
                GrayScaleImageHelper.CalculateMeanAndVarianceM9(
                    grayScaleImage.Width,
                    grayScaleImage.Height,
                    bitmapData.Stride,
                    grayScaleHW,

                    out imageTMean,
                    out imageTVariance);
                var current = new RadiometricSimilarityImage(grayScaleImage.Width,
                                                             grayScaleImage.Height,
                                                             bitmapData.Stride,
                                                             grayScaleHW,
                                                             imageTMean, imageTVariance);

                byte[,] motionData, stationaryData;
                Bitmap motionImage, stationaryImage;
                GrayScaleImageHelper.GetRadiometricSimmilarity(
                    _previous,
                    current,
                    RadiometricDifferenceThrethhold,
                    out motionData,
                    out motionImage,

                    out stationaryData,
                    out stationaryImage);
                {
                    using (motionImage)
                    {
                        _interceptor.Intercept(RadiometricSimmilarityFrameTFrameTMinus1Motion, ImageHelper.ToBytes(motionImage));
                    }

                    using (stationaryImage)
                    {
                        _interceptor.Intercept(RadiometricSimmilarityFrameTFrameTMinus1Stationary, ImageHelper.ToBytes(stationaryImage));
                    }

                    UpdateBackgroundOrForeground(
                        motionData,
                        grayScaleImage.Width,
                        grayScaleImage.Height,
                        bitmapData.Stride,
                        grayScaleHW,
                        out motionPresents,
                        out motionWH);
                }

                _previous = current;

                using (var image = GrayScaleImageHelper.FromWH(motionWH))
                {
                    _interceptor.Intercept(DifferenceImage, ImageHelper.ToBytes(image));
                }

                if (motionPresents)
                {
                    return("Movement detected!");
                }
            }
            return(null);
        }
 public ObjectData Get(ReferenceData reference) => get.Intercept(NewContext(reference), () => real.Get(reference)) as ObjectData;
示例#28
0
            public void Intercept(Castle.DynamicProxy.IInvocation castleInvocation)
            {
                var invocation = TranslateInvocation(castleInvocation);

                _interceptor.Intercept(invocation);
            }
示例#29
0
 public TOutput Handle(TInput input)
 => _innerInterceptor.Intercept(_innerHandler, input);
示例#30
0
 private void InterceptSyncMethod(IInvocation invocation, IInvocationProceedInfo proceedInfo)
 {
     _abpInterceptor.Intercept(new CastleMethodInvaocationAdapter(invocation, proceedInfo));
 }