Example #1
0
        public void Intercept(IInvocation invocation) {
            object instance = ActLikeExtensions.GetInstanceField(invocation.Proxy.GetType(), invocation.Proxy,
                "__target");

            var attr =
                (ActualTypeAttribute[])
                    invocation.GetConcreteMethod().GetCustomAttributes(typeof (ActualTypeAttribute), true);
            var arguments = new List<object>();

            for (int i = 0; i < invocation.Arguments.Length; i++) {
                var type = attr[0].Types[i];
                if (type == null || type == typeof (object))
                    arguments.Add(invocation.Arguments[i]);
                else {
                    var actLike = ActLikeExtensions.ActLike(invocation.Arguments[i], type);
                    arguments.Add(actLike);
                }
            }

            var memebers =
                instance.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            var inv = memebers.First(x => x.Name == invocation.GetConcreteMethod().Name);

            invocation.ReturnValue = inv.Invoke(instance, arguments.ToArray());
        }
        public void Intercept(IInvocation invocation)
        {
            var attributes1 = invocation.GetConcreteMethodInvocationTarget().GetCustomAttributes(typeof(BaseAttribute), true);
            var attributes2 = invocation.GetConcreteMethodInvocationTarget().DeclaringType.GetCustomAttributes(typeof(BaseAttribute), true);
            var attributes3 = invocation.GetConcreteMethod().GetCustomAttributes(typeof(BaseAttribute), true);
            var attributes4 = invocation.GetConcreteMethod().DeclaringType.GetCustomAttributes(typeof(BaseAttribute), true);

            var attributes = new object[attributes1.Length + attributes2.Length + attributes3.Length + attributes4.Length];

            attributes1.CopyTo(attributes, 0);
            attributes2.CopyTo(attributes, attributes1.Length);
            attributes3.CopyTo(attributes, attributes1.Length + attributes2.Length);
            attributes4.CopyTo(attributes, attributes1.Length + attributes2.Length + attributes3.Length);

            var attrList = new ArrayList();

            foreach (var attr in attributes)
            {
                if (!attrList.Contains(attr))
                {
                    attrList.Add(attr);
                }
            }

            if (attributes.Length == 0)
            {
                invocation.Proceed();
                return;
            }

            ExecIntercept(invocation, attrList);
        }
Example #3
0
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method = invocation.GetConcreteMethod();
            Type       type   = method.DeclaringType;

            if (method.DeclaringType.IsInterface)
            {
                string   serviceUrl = this.baseUrl + type.FullName;
                string   methodName = method.Name;
                object[] parameters = invocation.Arguments;

                // invoke JSONRPC via http
                string json = JsonrpcClient.invokeJson(serviceUrl, methodName, parameters);

                Console.WriteLine(json.ToString());
                Type retType = method.ReturnType;

                // deserializeResponseMessage and make generic
                MethodInfo dmethod = typeof(Json).GetMethod("deserializeResponseMessage");
                MethodInfo generic = dmethod.MakeGenericMethod(retType);

                // Json.deserializeResponseMessage(json)
                object respose = generic.Invoke(null, new object[] { json });

                // ResponseMessage.result
                // object ret = respose.GetType().GetProperty("result").GetValue(respose);

                invocation.ReturnValue = respose;
            }
        }
Example #4
0
        public void Intercept(IInvocation invocation)
        {
            this.log.InfoFormat("--- {0} start --- {1}",
                                invocation.Method.Name,
                                this.GetParameterString(invocation.GetConcreteMethod(), invocation.Arguments));

            try
            {
                invocation.Proceed();

                if (invocation.Method.ReturnType == null)
                {
                    this.log.Info("Return");
                }
                else
                {
                    this.log.InfoFormat("Return: {0}", this.serializer.Serialize(invocation.ReturnValue));
                }
            }
            catch (Exception ex)
            {
                this.log.Error(string.Format("Error in {0}", nameof(invocation.Method.Name)), ex);
                throw;
            }
        }
Example #5
0
        private LogDetail GetLogDetail(IInvocation invocation)
        {
            var userName      = _httpContextAccessor.HttpContext.User.ClaimUserName();
            var remoteIp      = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            var logParameters = new List <LogParameter>();

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                logParameters.Add(new LogParameter
                {
                    Name  = invocation.GetConcreteMethod().GetParameters()[i].Name,
                    Value = invocation.Arguments[i],
                    Type  = invocation.Arguments[i].GetType().Name
                });
            }

            var logDetail = new LogDetail {
                MethodName     = invocation.Method.Name,
                LogParameters  = logParameters,
                RequestingName = userName,
                Ip             = remoteIp
            };

            return(logDetail);
        }
Example #6
0
        public void Intercept(IInvocation invocation)
        {
            string interfaceShortName = invocation.Method.DeclaringType.Name;
            string interfaceFullname  = invocation.Method.DeclaringType.FullName;
            string methodName         = invocation.Method.Name;

            List <ParameterInfo> parameterInfo = new List <ParameterInfo>(invocation.GetConcreteMethod().GetParameters());

            System.Diagnostics.Trace.WriteLine($"{interfaceFullname}.{methodName}, Method arguments: " + string.Join(", ", parameterInfo.Select(a => a.Name)));

            ParameterInfo item = parameterInfo.FirstOrDefault(a => a.Name == "merchantId");

            if (item != null)
            {
                int argumentPositionByName = parameterInfo.IndexOf(item);

                int merchantId       = Convert.ToInt32(invocation.Arguments[argumentPositionByName]);
                int targetMerchantId = 3;

                // translate original id to another id
                invocation.Arguments[argumentPositionByName] = targetMerchantId;

                System.Diagnostics.Trace.WriteLine($"translated {merchantId} to {targetMerchantId}");
            }

            invocation.Proceed(); //Intercepted method is executed here.
        }
        private LogDetailWithException GetLogDetail(IInvocation invocation)
        {
            var logPrameters = new List <LogParameter>();

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                logPrameters.Add(new LogParameter()
                {
                    Name  = invocation.GetConcreteMethod().GetParameters()[i].Name,
                    Value = "*", // the content of 'value' is confidential because it may contain important information
                    Type  = invocation.Arguments[i].GetType().Name
                });
            }

            var claimNameIdendifier = httpContextAccessor.HttpContext.User.NameIdentifier();

            var logDetailWithException = new LogDetailWithException()
            {
                MethodName    = $"{invocation.Method.ReflectedType.Name}.{invocation.Method.Name}",
                ClaimId       = claimNameIdendifier,
                LogParameters = logPrameters
            };

            return(logDetailWithException);
        }
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.GetConcreteMethod();

            method = invocation.InvocationTarget.GetType().
                     GetMethod(method.Name);

            if (method != null)
            {
                var attribute = method.GetCustomAttribute <MyLogAttribute>();
                try
                {
                    if (attribute != null)
                    {
                        Console.WriteLine("Starting the log");
                        invocation.Proceed();

                        Console.WriteLine("Ending the log");
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occurred: " + ex);
                }
            }
        }
Example #9
0
 public void Intercept(TransactionAttribute attribute, IInvocation invocation)
 {
     if (attribute != null)
     {
         //事务过期和级别信息
         TransactionOptions transactionOptions = new TransactionOptions()
         {
             IsolationLevel = Enum.Parse <IsolationLevel>(attribute.Level.GetEnumValue().ToString()),
             Timeout        = attribute.TimeoutSecond.HasValue ? new TimeSpan(0, 0, attribute.TimeoutSecond.Value) : new TimeSpan(0, 0, 10)
         };
         using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
         {
             try
             {
                 invocation.Proceed();
                 transactionScope.Complete();
             }
             catch (Exception ex)
             {
                 string methodName = invocation.GetConcreteMethod().Name;
                 string logger     = string.Format("TransactionInterceptor:{0}", methodName);
                 LogUtils.LogError(ex, logger, ex.Message);
             }
             finally
             {
                 transactionScope.Dispose();
             }
         }
     }
 }
        /// <inheritdoc />
        public override void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var unitOfWorkOptions = GetUnitOfWorkAttribute(method);

            if (unitOfWorkOptions == null)
            {
                //No need to a uow
                invocation.Proceed();
                return;
            }

            //No current uow, run a new one
            PerformUow(invocation, unitOfWorkOptions);
        }
Example #11
0
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var disableUnitOfWorkAttribute = invocation.Method.GetCustomAttribute(typeof(DisableUnitOfWorkAttribute));

            if (disableUnitOfWorkAttribute != null)
            {
                invocation.Proceed();
                return;
            }

            var enableUnitofWorkAttribute = this.GetEnableUnitOfWorkAttributeOrNull(invocation.Method);

            if (enableUnitofWorkAttribute != null)
            {
                ProccessUnitOfWork(invocation, enableUnitofWorkAttribute.UnitOfWorkOptions);
            }
            else
            {
                invocation.Proceed();
                return;
            }
        }
Example #12
0
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            UnitOfWorkAttribute attribute = GetUnitOfWorkAttributeOrNull(method);

            if (attribute == null || attribute.IsDisabled)
            {
                //No need to a uow
                invocation.Proceed();
                return;
            }

            //No current uow, run a new one
            PerformUow(invocation, attribute.CreateOptions());
        }
Example #13
0
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.GetConcreteMethod();
            //var targetType = GetNestedType(invocation.InvocationTarget);
            var targetType = GetNestedType(invocation.Proxy) ?? GetNestedType(invocation.InvocationTarget);


            try
            {
                System.Diagnostics.Debug.WriteLine("Exception interceptor {0}.{1}.{2}", targetType.Assembly.GetName().Name, targetType.Name, method.Name);

                invocation.Proceed();
            }
            catch (Exception ex)
            {
                var args = String.Join(", ", invocation.Arguments);
                var msg  = new StringBuilder();

                msg.AppendFormat("Exception occurred in {0}.{1}.{2}", targetType.Assembly.GetName().Name, targetType.Name, method.Name).AppendLine();
                msg.AppendFormat("With the following arguments: {0}", args).AppendLine();
                msg.AppendLine(ex.ToString());

                System.Diagnostics.Debug.WriteLine(msg.ToString());

                throw ex;
            }
        }
Example #14
0
        protected override string StartingInvocation(IInvocation invocation)
        {
            var method = invocation.GetConcreteMethod().Name;
            var arg    = invocation.Arguments[0];

            return($"intercept BEFORE async method call of `{method}` with argument `{arg}`; ");
        }
        private LogDetail GetLogDetail(IInvocation invocation)
        {
            var logPrameters = new List <LogParameter>();

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                logPrameters.Add(new LogParameter()
                {
                    Name  = invocation.GetConcreteMethod().GetParameters()[i].Name,
                    Value = invocation.Arguments[i],
                    Type  = invocation.Arguments[i].GetType().Name
                });
            }

            var claimNameIdendifier = httpContextAccessor.HttpContext.User.NameIdentifier();

            var logDetail = new LogDetail()
            {
                MethodName    = $"{invocation.Method.ReflectedType.Name}.{invocation.Method.Name}",
                ClaimId       = claimNameIdendifier,
                LogParameters = logPrameters
            };

            return(logDetail);
        }
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var attribute = FindTransactionalAttribute(method);

            //If there is a running transaction, just run the method
            if (!attribute.HasValue || _dbContext.HasTransaction)
            {
                invocation.Proceed();
                return;
            }

            _logger.LogInformation($"Starting Interception {invocation.TargetType?.FullName}.{method.Name}");

            Intercept(invocation, attribute.Value);

            _logger.LogInformation($"Finished Interception {invocation.TargetType?.FullName}.{method.Name}");
        }
Example #17
0
        private string GetLogDetail(IInvocation invocation)
        {
            var logParameters = new List <LogParameter>();

            for (var i = 0; i < invocation.Arguments.Length; i++)
            {
                logParameters.Add(new LogParameter
                {
                    Name  = invocation.GetConcreteMethod().GetParameters()[i].Name,
                    Value = invocation.Arguments[i],
                    Type  = invocation.Arguments[i].GetType().Name,
                });
            }

            var logDetail = new LogDetail
            {
                MethodName = invocation.Method.Name,
                Parameters = logParameters,
                User       = (_httpContextAccessor.HttpContext == null ||
                              _httpContextAccessor.HttpContext.User.Identity.Name == null)
                    ? "?"
                    : _httpContextAccessor.HttpContext.User.Identity.Name
            };

            return(JsonConvert.SerializeObject(logDetail));
        }
Example #18
0
        protected override void CompletedInvocation(IInvocation invocation, string state)
        {
            var method = invocation.GetConcreteMethod().Name;
            var res    = invocation.ReturnValue;

            Interseptions.Add(state + "intercept AFTER async method call of `{methodName}` with the result `{res}`;");
        }
Example #19
0
        /// <summary>
        /// 截取一个方法。
        /// </summary>
        /// <param name="invocation">方法调用参数</param>
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var unitOfWorkAttr = _unitOfWorkOptions.GetUnitOfWorkAttributeOrNull(method);

            if (unitOfWorkAttr == null || unitOfWorkAttr.IsDisabled)
            {
                //不需要UOW
                invocation.Proceed();
                return;
            }

            //没有当前UOW,运行新的UOW
            PerformUow(invocation, unitOfWorkAttr.CreateOptions());
        }
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var failures = _validator.Validate(method, invocation.Arguments);
            var result   = failures.ToResult();

            if (!result.Failed)
            {
                invocation.Proceed();
                return;
            }

            if (invocation.Method.IsAsync())
            {
                InterceptAsync(invocation, result);
            }
            else
            {
                InterceptSync(invocation, result);
            }
        }
Example #21
0
        public void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }

            var unitOfWorkAttr = _unitOfWorkOptions.GetUnitOfWorkAttributeOrNull(method);

            if (unitOfWorkAttr == null || unitOfWorkAttr.IsDisabled)
            {
                invocation.Proceed();
                return;
            }

            var options = unitOfWorkAttr.CreateOptions();

            using (var uow = _unitOfWorkManager.Begin(options))
            {
                invocation.Proceed();
                uow.Complete();
            }

            //using (var ts = new TransactionScope())//创建一个事务范围对象
            //{
            //    invocation.Proceed();//执行被拦截的方法
            //    ts.Complete();//事务完成
            //}
        }
Example #22
0
        /// <summary>
        /// Intercepts and performs timing logic
        /// </summary>
        /// <param name="invocation">current invocation site</param>
        /// <param name="attributes">transaction attributes</param>
        protected override void OnIntercepted(IInvocation invocation, TransactionScopeAttribute[] attributes)
        {
            invocation = Arguments.EnsureNotNull(invocation, nameof(invocation));

            try
            {
                var esio = EnterpriseServicesInteropOption.None;

                using var ts = new TransactionScope(this.scopeOption, this.options, esio);

                invocation.Proceed();

                var stopwatch = Stopwatch.StartNew();

                ts.Complete();

                var timeSpan = stopwatch.ElapsedMilliseconds;

                this.Logger.Debug("COMMIT:{0} Duration(ms):{1}", invocation.GetConcreteMethod(), timeSpan);
            }
            catch (Exception ex)
            {
                this.Logger.Error(ex, "ROLLBACK:{0} Message:{1}", invocation.GetMethodName(), ex.Message);
                throw;
            }
        }
    public static MethodInfo GetImplementationMethod(this IInvocation invocation)
    {
        // NOTE: bit naive implementation
        var method = invocation.GetConcreteMethod();

        return(invocation.InvocationTarget.GetType().GetMethod(method.Name));
    }
        /// <inheritdoc />
        public override void Intercept(IInvocation invocation)
        {
            MethodInfo method;

            try
            {
                method = invocation.MethodInvocationTarget;
            }
            catch
            {
                method = invocation.GetConcreteMethod();
            }
            Exception error = null;

            try
            {
                invocation.Proceed();
            }
            catch (Exception ex)
            {
                error = ex;
                throw;
            }
            finally
            {
                var auditLogAttribute = GetAuditLogAttribute(method);
                if (!auditLogAttribute.IsDisabled)
                {
                    _logger.LogInformation($"ClassName:{method.DeclaringType},MethodName:{method.Name},args:{invocation.Arguments.ToString()},return value:{invocation.ReturnValue},error:{error?.Message}");
                }
            }
        }
Example #25
0
        private LogDetail GetLogDetail(IInvocation invocation)
        {
            var logParameters = new List <LogParameter>();

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                logParameters.Add(new LogParameter
                {
                    Name  = invocation.GetConcreteMethod().GetParameters()[i].Name,
                    Value = invocation.Arguments[i],
                    Type  = invocation.Arguments[i].GetType().Name
                });
            }

            //var logParameters = invocation.Arguments.Select(x => new LogParameter
            //{
            //    Value = x,
            //    Type = x.GetType().Name
            //}).ToList();

            var logDetail = new LogDetail
            {
                MethodName    = invocation.Method.Name,
                LogParameters = logParameters
            };

            return(logDetail);
        }
Example #26
0
        ///<summary>
        ///</summary>
        public void PerformAgainst(IInvocation invocation)
        {
            object     proxy  = mockRepository.GetMockObjectFromInvocationProxy(invocation.Proxy);
            MethodInfo method = invocation.GetConcreteMethod();

            invocation.ReturnValue = mockRepository.MethodCall(invocation, proxy, method, invocation.Arguments);
        }
Example #27
0
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.TargetType.FullName + "." + invocation.GetConcreteMethod().Name;

            _logger.Debug( GetDateInLogFormat() + " " + methodName + " Entered");
            invocation.Proceed();
            _logger.Debug( GetDateInLogFormat() + " " + methodName + " Exited");
        }
        public void Intercept(IInvocation invocation)
        {
            // Perform logging here, e.g.:
            var args = string.Join(", ", invocation.Arguments.Select(x => (x ?? string.Empty).ToString()));
            Debug.WriteLine(string.Format("SimpleInjector: {0}({1})", invocation.GetConcreteMethod().Name, args));

            invocation.Proceed();
        }
Example #29
0
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.TargetType.FullName + "." + invocation.GetConcreteMethod().Name;

            _logger.Debug(GetDateInLogFormat() + " " + methodName + " Entered");
            invocation.Proceed();
            _logger.Debug(GetDateInLogFormat() + " " + methodName + " Exited");
        }
Example #30
0
            public void Intercept(IInvocation invocation)
            {
                // Perform logging here, e.g.:
                var args = string.Join(", ", invocation.Arguments.Select(x => x + string.Empty));

                Debug.WriteLine("DryIocInterceptor: {0}({1})", invocation.GetConcreteMethod().Name, args);
                invocation.Proceed();
            }
Example #31
0
        public void Intercept(IInvocation invocation)
        {
            // Perform logging here, e.g.:
            var args = string.Join(", ", invocation.Arguments.Select(x => (x ?? string.Empty).ToString()));

            Debug.WriteLine(string.Format("SimpleInjector: {0}({1})", invocation.GetConcreteMethod().Name, args));

            invocation.Proceed();
        }
Example #32
0
        public override void Intercept(IInvocation invocation)
        {
            MethodInfo methodInfo;

            try
            {
                methodInfo = invocation.MethodInvocationTarget;
            }
            catch
            {
                methodInfo = invocation.GetConcreteMethod();
            }

            if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute))
            {
                invocation.Proceed();
            }
            else
            {
                using (var unitOfWork = _unitOfWorkManager.Begin(CreateOptions(invocation, unitOfWorkAttribute)))
                {
                    invocation.Proceed();
                    if (!invocation.Method.IsAsync())
                    {
                        unitOfWork.Complete();
                    }
                    else
                    {
                        if (invocation.Method.ReturnType == typeof(Task))
                        {
                            invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                                (Task)invocation.ReturnValue,
                                async() =>
                            {
                                await unitOfWork.CompleteAsync();
                                await Task.FromResult(0);
                            },
                                exception => unitOfWork.Dispose()
                                );
                        }
                        else //Task<TResult>
                        {
                            invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                                invocation.Method.ReturnType.GenericTypeArguments[0],
                                invocation.ReturnValue,
                                async() =>
                            {
                                await unitOfWork.CompleteAsync();
                                await Task.FromResult(0);
                            },
                                exception => unitOfWork.Dispose()
                                );
                        }
                    }
                }
            }
        }
Example #33
0
        /// <summary>
        /// Gets the method name for the current IInvocation object
        /// </summary>
        /// <param name="invocation">IInvocation being extended</param>
        /// <returns>method name</returns>
        public static string GetMethodName(this IInvocation invocation)
        {
            invocation = Arguments.EnsureNotNull(invocation, nameof(invocation));

            var targetType     = invocation.TargetType;
            var concreteMethod = invocation.GetConcreteMethod();

            return(targetType.FullName + "." + concreteMethod.Name);
        }
Example #34
0
        public void Intercept(IInvocation invocation)
        {
            var attr = invocation.GetConcreteMethod().GetCustomAttributes(typeof(CacheAttribute),false);
            var cacheAttr = attr[0] as CacheAttribute;
            var key = cacheAttr.Key;

            //get data from cache

            invocation.ReturnValue = 10;

            //if not call the invocation.Proceed() the function will not really exec
        }
        public void Intercept(IInvocation invocation)
        {
            // Calls the decorated instance.
            invocation.Proceed();


            if (invocation.GetConcreteMethod().Name ==
                NameOfHelper.MethodName<IUrlTrackingService>(x => x.TrackAsync(null)))
            {
                // TrackAsync called
                var trackTask = (Task<UrlTrackingResult>)invocation.ReturnValue;

                // Filtering bots
                if (HttpContext.Current != null)
                {
                    string userAgent = HttpContext.Current.Request.UserAgent;
                    if (!string.IsNullOrEmpty(userAgent))
                    {
                        if (_bots.Any(bot => userAgent.IndexOf(bot, StringComparison.InvariantCultureIgnoreCase) >= 0))
                        {
                            return;
                        }
                    }
                }

                // Checking result
                trackTask.ContinueWith(async t =>
                {
                    UrlTrackingResult trackingResult = t.Result;
                    if (!trackingResult.IsAccountable)
                    {
                        // skip non tariffing redirects
                        return;
                    }

                    try
                    {
                        DomainTrackingStat trackingStat = _mappingEngine.Map<UrlTrackingResult, DomainTrackingStat>(trackingResult);

                        // counting url
                        await _service.CountAsync(trackingStat);
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError(string.Format("Could not count external url '{0}': {1}",
                            trackingResult.Redirect, e));
                    }
                });
            }
        }
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.TargetType.FullName + "." + invocation.GetConcreteMethod().Name;

            var arglist = String.Join(", ", invocation.Arguments.Select(arg => arg != null ? arg.ToString() : "<null>"));
            Debug.WriteLine(string.Format("{0}: Entering Campfire API method {1}({2})", Thread.CurrentThread.ManagedThreadId, methodName,
                                          arglist));

            var stopwatch = Stopwatch.StartNew();

            invocation.Proceed();

            Debug.WriteLine("{0}: Leaving Campfire API method {1}({2}). Time taken: {3}",
                            Thread.CurrentThread.ManagedThreadId, methodName, arglist, stopwatch.Elapsed);
        }
		public void Intercept(IInvocation invocation)
		{
			this.invocation = invocation;
			MethodInfo concreteMethod = invocation.GetConcreteMethod();

			if (invocation.MethodInvocationTarget != null)
			{
				invocation.Proceed();
			}
			else if (concreteMethod.ReturnType.IsValueType && !concreteMethod.ReturnType.Equals(typeof(void)))
			// ensure valid return value
			{
				invocation.ReturnValue = Activator.CreateInstance(concreteMethod.ReturnType);
			}
		}
		public void Intercept(IInvocation invocation)
		{
			if (ProfilerInterceptor.ReentrancyCounter > 0)
			{
				CallOriginal(invocation, false);
				return;
			}

			bool callOriginal = false;
			ProfilerInterceptor.GuardInternal(() =>
			{
				var mockInvocation = new Invocation
				{
					Args = invocation.Arguments,
					Method = invocation.GetConcreteMethod(),
					Instance = invocation.Proxy,
				};

				DebugView.TraceEvent(IndentLevel.Dispatch, () => String.Format("Intercepted DP call: {0}", mockInvocation.InputToString()));
				DebugView.PrintStackTrace();

				var mock = MocksRepository.GetMockMixin(invocation.Proxy, invocation.Method.DeclaringType);
				var repo = mock != null ? mock.Repository : this.constructionRepo;

				lock (repo)
				{
					repo.DispatchInvocation(mockInvocation);
				}

				invocation.ReturnValue = mockInvocation.ReturnValue;
				callOriginal = mockInvocation.CallOriginal;

				if (callOriginal)
				{
					DebugView.TraceEvent(IndentLevel.DispatchResult, () => "Calling original implementation");
				}
				else if (mockInvocation.IsReturnValueSet)
				{
					DebugView.TraceEvent(IndentLevel.DispatchResult, () => String.Format("Returning value '{0}'", invocation.ReturnValue));
				}
			});

			if (callOriginal)
				CallOriginal(invocation, true);
		}
        public void Intercept(IInvocation invocation)
        {
            var action = invocation.Method.Name;
            var controller = invocation.TargetType.Name.Replace("Controller", "");

            var values = new Dictionary<string, object>();
            var argValues = invocation.Arguments.GetEnumerator();
            foreach (var argument in invocation.GetConcreteMethod().GetParameters())
            {
                argValues.MoveNext();
                if (argValues.Current != null)
                {
                    values.Add(argument.Name, argValues.Current);
                }
            }

            relations.AddToAction(controller, action, values);
        }
        public void Intercept(IInvocation invocation)
        {
            if (instance.ProxyInstance == null)
            {
                invocation.Proceed();
                return;
            }

            var container = instance as IMockExpectationContainer;
            if (container == null)
            {
                invocation.ReturnValue = null;
                return;
            }

            var method = invocation.GetConcreteMethod();
            var arguments = invocation.Arguments;
            var type = method.ReturnType;

            if (container.ExpectationMarked)
            {
                RhinoMocks.Logger.LogExpectation(invocation);

                var expectation = container.GetMarkedExpectation();
                if (expectation.ReturnType.Equals(type))
                {
                    expectation.HandleMethodCall(method, arguments);
                    invocation.ReturnValue = IdentifyDefaultValue(type);
                    return;
                }
                
                var recursive = ParseRecursiveExpectation(container, expectation, type);
                recursive.HandleMethodCall(method, arguments);
                invocation.ReturnValue = recursive.ReturnValue;
                return;
            }

            invocation.ReturnValue = container
                .HandleMethodCall(invocation, method, arguments);
        }
            /// <summary>
            /// Intercepts calls to methods on the class.
            /// </summary>
            /// <param name="invocation">An IInvocation object describing the actual implementation.</param>
            public void Intercept(IInvocation invocation)
            {
                if (invocation == null)
                {
                    throw new ArgumentNullException("invocation", "invocation cannot be null");
                }

                if (invocation.Method.Name == "get_WrappedElement")
                {
                    invocation.ReturnValue = this.WrappedElement;
                }
                else if (invocation.Method.Name == "get_LocationOnScreenOnceScrolledIntoView" || invocation.Method.Name == "get_Coordinates")
                {
                    invocation.ReturnValue = invocation.GetConcreteMethod().Invoke(this.WrappedElement as ILocatable, invocation.Arguments);
                }
                else
                {
                    invocation.ReturnValue = invocation.GetConcreteMethod().Invoke(this.WrappedElement, invocation.Arguments);
                }
            }
Example #42
0
 public void Intercept(IInvocation invocation)
 {
     proxyInstance.MockedObjectInstance = invocation.Proxy;
     if (Array.IndexOf(objectMethods, invocation.Method) != -1)
     {
         invocation.Proceed();
         return;
     }
     if (invocation.Method.DeclaringType == typeof (IMockedObject))
     {
         invocation.ReturnValue = invocation.Method.Invoke(proxyInstance, invocation.Arguments);
         return;
     }
     if (proxyInstance.ShouldCallOriginal(invocation.GetConcreteMethod()))
     {
         invocation.Proceed();
         return;
     }
     if (proxyInstance.IsPropertyMethod(invocation.GetConcreteMethod()))
     {
         invocation.ReturnValue = proxyInstance.HandleProperty(invocation.GetConcreteMethod(), invocation.Arguments);
         repository.RegisterPropertyBehaviorOn(proxyInstance);
         return;
     }
     //This call handle the subscribe / remove this method call is for an event,
     //processing then continue normally (so we get an expectation for subscribing / removing from the event
     HandleEvent(invocation, invocation.Arguments);
     object proxy = repository.GetMockObjectFromInvocationProxy(invocation.Proxy);
     MethodInfo method = invocation.GetConcreteMethod();
     invocation.ReturnValue = repository.MethodCall(invocation, proxy, method, invocation.Arguments);
 }
        private string GetParameterStrings(IInvocation invocation)
        {
            string parameterStrings = "";

            try
            {
                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    var parameterInfo = invocation.GetConcreteMethod().GetParameters()[i];
                    var parameterValue = invocation.Arguments[i];
                    var detailString = (parameterValue != null) ? parameterValue.ToString() : "null";
                    parameterStrings += (string.Format("[name:{0}, type:{1}, value:{2}] ",
                                                       parameterInfo.Name, parameterInfo.ParameterType.Name,
                                                       detailString.Replace("\r\n", " ")));
                }
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("LoggingInterceptor.GetParameterStrings() threw an error: {0}; StackTrace: {1}",
                                                            ex.Message, ex.StackTrace);
                LogNow(invocation.Method.DeclaringType, errorMsg);
            }
            return parameterStrings;
        }
Example #44
0
 ///<summary>
 ///</summary>
 public void PerformAgainst(IInvocation invocation)
 {
     object proxy = mockRepository.GetMockObjectFromInvocationProxy(invocation.Proxy);
     MethodInfo method = invocation.GetConcreteMethod();
     invocation.ReturnValue = mockRepository.MethodCall(invocation, proxy, method, invocation.Arguments);
 }
Example #45
0
 ///<summary>
 ///</summary>
 public void PerformAgainst(IInvocation invocation)
 {
     invocation.ReturnValue = proxyInstance.HandleProperty(invocation.GetConcreteMethod(), invocation.Arguments);
     mockRepository.RegisterPropertyBehaviorOn(proxyInstance);
     return;
 }
Example #46
0
 /// <summary>
 /// Intercepts calls to methods on the class.
 /// </summary>
 /// <param name="invocation">An IInvocation object describing the actual implementation.</param>
 public void Intercept(IInvocation invocation)
 {
     if (invocation.Method.Name == "get_WrappedElement")
     {
         invocation.ReturnValue = this.WrappedElement;
     }
     else
     {
         invocation.ReturnValue = invocation.GetConcreteMethod().Invoke(this.WrappedElement, invocation.Arguments);
     }
 }
Example #47
0
            /// <summary>
            /// Intercepts calls to methods on the class.
            /// </summary>
            /// <param name="invocation">An IInvocation object describing the actual implementation.</param>
            public void Intercept(IInvocation invocation)
            {
                if (invocation == null)
                {
                    throw new ArgumentNullException("invocation", "invocation cannot be null");
                }

                if (invocation.Method.Name == "get_WrappedElement")
                {
                    invocation.ReturnValue = this.WrappedElement;
                }
                else
                {
                    invocation.ReturnValue = invocation.GetConcreteMethod().Invoke(this.WrappedElement, invocation.Arguments);
                }
            }
Example #48
0
 public void Intercept(IInvocation invocation)
 {
     // Perform logging here, e.g.:
     var args = string.Join(", ", invocation.Arguments.Select(x => x + string.Empty));
     Debug.WriteLine("DryIocInterceptor: {0}({1})", invocation.GetConcreteMethod().Name, args);
     invocation.Proceed();
 }