public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.Name == "get_Rules")
            {
                return(getNext()(input, getNext));
            }

            var processRuleAttribute = input.MethodBase.CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof(ProcessRules));
            var rulesInterface       = input.Target as IDomainAggregate <T>;

            if (processRuleAttribute == null || rulesInterface == null)
            {
                return(getNext()(input, getNext));
            }

            var target = (T)input.Target;

            var advise = (ProcessRulesAdvise)processRuleAttribute.ConstructorArguments.Single().Value;

            if (advise == ProcessRulesAdvise.Before || advise == ProcessRulesAdvise.Around)
            {
                RunRules(rulesInterface, target);
            }

            IMethodReturn result = getNext()(input, getNext);

            if (advise == ProcessRulesAdvise.After || advise == ProcessRulesAdvise.Around)
            {
                RunRules(rulesInterface, target);
            }

            return(result);
        }
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>
        /// Return value from the target.
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase == AddEventMethodInfo)
            {
                return(AddEventSubscription(input));
            }

            if (input.MethodBase == RemoveEventMethodInfo)
            {
                return(RemoveEventSubscription(input));
            }

            if (input.MethodBase.Name == "get_IsChangeNotificationActive")
            {
                return(input.CreateMethodReturn(_isChangeNotificationActive));
            }

            if (input.MethodBase.Name == "set_IsChangeNotificationActive")
            {
                _isChangeNotificationActive = (bool)input.Arguments[0];
                return(input.CreateMethodReturn(null));
            }

            if (_isChangeNotificationActive && IsSetter(input) && IsChange(input))
            {
                IMethodReturn result       = getNext()(input, getNext);
                string        propertyName = input.MethodBase.Name.Substring(4);

                NotifyPropertyChanged(propertyName, input);
                NotifyAdditionalProperties(input, propertyName);

                return(result);
            }
            return(getNext()(input, getNext));
        }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        IMethodReturn result = getNext()(input, getNext);

        Console.WriteLine("Interception Called");
        return(result);
    }
        private string PringReturnValue(IMethodReturn result)
        {
            if (null == result.ReturnValue)
                return "null";

            return result.ReturnValue.ToString();
        }
Exemple #5
0
        private void LogCallToContainer(IMethodInvocation input, IMethodReturn result)
        {
            string message = string.Empty;

            if (result.Exception != null)
            {
                message = $"threw exception {result.Exception.Message}";
            }
            else
            {
                switch (input.MethodBase.Name)
                {
                case nameof(IContainer.GetItemValue):
                    message += $"the value at \"{input.Arguments[0]}\" is \"{((IDriveItem)result.ReturnValue).FullName}\"";
                    break;

                case nameof(IContainer.GetChildItems):
                    message += $"child items are {string.Join(",", ((IEnumerable<IDriveItem>)result.ReturnValue).Select(p => $"\"{p.FullName}\""))}.";
                    break;
                }
            }

            Stopwatch sw = (Stopwatch)result.InvocationContext[PerformanceMeasurementHandler.PerformanceKey];

            WriteLog($"{DateTime.Now:hh:MM:ss} \"{((IContainer)input.Target).FullName}\" ({sw.Elapsed.TotalSeconds:0.00000}): {message}");
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn methodReturn = null;

            if (input.Arguments.Count > 0 &&
                null != input.Arguments[0])
            {
                object oldValue = null, newValue = null;
                if (ShouldRaiseEvent(input, ref oldValue, ref newValue))
                {
                    methodReturn = getNext()(input, getNext);
                    if (input.Target is INotifyPropertyChanged &&
                        methodReturn.Exception == null)
                    {
                        var propertyName = input.MethodBase.Name.Substring(4);
                        (input.Target as INotifyPropertyChanged).RaisePropertyChangedEvent(this, new PropertyChangedEventArgs(propertyName, oldValue, newValue));
                    }
                }
            }
            else
            {
                methodReturn = getNext().Invoke(input, getNext);
            }

            return(methodReturn);
        }
        /// <summary>
        /// Executes the handler. Increments the various counter according to configuration.
        /// </summary>
        /// <param name="input"><see cref="IMethodInvocation"/> describing the current call.</param>
        /// <param name="getNext">delegate to call to get the next handler in the pipeline.</param>
        /// <returns>Return value from target method.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (getNext == null)
            {
                throw new ArgumentNullException("getNext");
            }

            string[] instanceNames = GetInstanceNames(input);

            IncrementItemCounter(incrementNumberOfCalls, NumberOfCallsCounterName, instanceNames);
            IncrementItemCounter(incrementCallsPerSecond, CallsPerSecondCounterName, instanceNames);

            long start = Stopwatch.GetTimestamp();

            IMethodReturn result = getNext()(input, getNext);

            long end = Stopwatch.GetTimestamp();

            IncrementAverageCounter(incrementAverageCallDuration,
                                    end - start,
                                    AverageCallDurationCounterName,
                                    AverageCallDurationBaseCounterName,
                                    instanceNames);

            if (result.Exception != null)
            {
                IncrementItemCounter(incrementTotalExceptions, TotalExceptionsCounterName, instanceNames);
                IncrementItemCounter(incrementExceptionsPerSecond, ExceptionsPerSecondCounterName,
                                     instanceNames);
            }

            return(result);
        }
Exemple #8
0
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>
        /// Return value from the target.
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0}.{1}(", input.Target.GetType().Name, input.MethodBase.Name);

            if (input.Arguments.Count > 0)
            {
                for (int i = 0; i < input.Inputs.Count; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }

                    sb.AppendFormat("{0}:{1}", input.Inputs.ParameterName(i), input.Inputs[i].ToString());
                }
            }

            sb.Append(")");

            this._logger.Trace("Before: " + sb.ToString());

            IMethodReturn msg = getNext()(input, getNext);

            if (msg.Exception != null)
            {
                this._logger.Error(msg.Exception);

                RecurseError(msg.Exception);
            }

            this._logger.Trace("After: " + sb.ToString());
            return(msg);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            ISession session = SessionFactory.GetCurrentSession();

            ITransaction transaction = null;

            if (IsolationLevel == IsolationLevel.Unspecified)
            {
                transaction = session.BeginTransaction();
            }
            else
            {
                transaction = session.BeginTransaction(IsolationLevel);
            }
            Debug.WriteLine("Started transaction");

            IMethodReturn result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                transaction.Rollback();
                Debug.WriteLine("Rolled transaction");
            }
            else
            {
                transaction.Commit();
                Debug.WriteLine("Committed transaction");
            }
            transaction.Dispose();

            return(result);
        }
        /// <summary>
        /// Effectue l'appel de la méthode, inscrit l'exception dans le log si erreur, sinon mesure du temps.
        /// </summary>
        /// <param name="input">Méthode cible de l'appel.</param>
        /// <param name="getNext">Delegate.</param>
        /// <returns>Valeur de retour de la cible.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (getNext == null)
            {
                throw new ArgumentNullException("getNext");
            }

            ILog      log   = LogManager.GetLogger("Service");
            Stopwatch watch = Stopwatch.StartNew();

            watch.Start();
            IMethodReturn retValue = getNext()(input, getNext);

            watch.Stop();
            if (retValue.Exception != null)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Erreur sur le service " + input.MethodBase.DeclaringType.FullName + "." + input.MethodBase.Name, retValue.Exception);
                }
            }
            else if (log.IsInfoEnabled)
            {
                log.InfoFormat("Service {0}.{1}.{2}", input.MethodBase.DeclaringType.FullName, input.MethodBase.Name, watch.Elapsed.Seconds);
            }

            return(retValue);
        }
Exemple #11
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            this.source.TraceInformation(
                "Invoking {0}",
                input.MethodBase.ToString());

            IMethodReturn methodReturn = getNext().Invoke(input, getNext);

            if (methodReturn.Exception == null)
            {
                this.source.TraceInformation(
                    "Successfully finished {0}",
                    input.MethodBase.ToString());
            }
            else
            {
                this.source.TraceInformation(
                    "Finished {0} with exception {1}: {2}",
                    input.MethodBase.ToString(),
                    methodReturn.Exception.GetType().Name,
                    methodReturn.Exception.Message);
            }

            this.source.Flush();

            return(methodReturn);
        }
Exemple #12
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);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            // Before invoking the method on the original target.
            if (input.MethodBase.Name == "GetConnectionString")
            {
                var key = input.Arguments["key"].ToString();
                if (IsInCache(key))
                {
                    return(input.CreateMethodReturn(FetchFromCache(key)));
                }
                else
                {
                    IMethodReturn routine = getNext()(input, getNext);
                    //Task.Run(() =>
                    //{
                    //    AddToCache(key, routine.ReturnValue.ToString());
                    //});
                    AddToCache(key, routine.ReturnValue.ToString());
                    return /*input.CreateMethodReturn(result.ReturnValue.ToString())*/ (routine);
                }
            }
            IMethodReturn result = getNext()(input, getNext);

            // After invoking the method on the original target.
            //if (input.MethodBase.Name == "SaveConnectionString")
            //{
            //    AddToCache(input.Arguments["key"].ToString(), input.Arguments["val"].ToString());
            //}
            return(result);
        }
Exemple #14
0
        public override IMessage Invoke(IMessage msg)
        {
            Guard.ArgumentNotNull(msg, "msg");

            IMethodCallMessage callMessage = (IMethodCallMessage)msg;

            if (callMessage.MethodBase.DeclaringType == typeof(IInterceptingProxy))
            {
                return(HandleInterceptingProxyMethod(callMessage));
            }

            HandlerPipeline pipeline = GetPipeline(TranslateInterfaceMethod(callMessage.MethodBase));

            TransparentProxyMethodInvocation invocation = new TransparentProxyMethodInvocation(callMessage, target);
            IMethodReturn result =
                pipeline.Invoke(
                    invocation,
                    delegate(IMethodInvocation input, GetNextHandlerDelegate getNext)
            {
                try
                {
                    object returnValue = callMessage.MethodBase.Invoke(target, invocation.Arguments);
                    return(input.CreateMethodReturn(returnValue, invocation.Arguments));
                }
                catch (TargetInvocationException ex)
                {
                    // The outer exception will always be a reflection exception; we want the inner, which is
                    // the underlying exception.
                    return(input.CreateExceptionMethodReturn(ex.InnerException));
                }
            });

            return(((TransparentProxyMethodReturn)result).ToMethodReturnMessage());
        }
Exemple #15
0
        /// <summary>
        /// Process the output from the call so far and optionally modify the output.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="methodReturn">The method return.</param>
        /// <param name="callData">The per-call data.</param>
        /// <returns>IMethodReturn.</returns>
        protected override IMethodReturn PostInvoke(
            IMethodInvocation input,
            IMethodReturn methodReturn,
            CallTraceData callData)
        {
            // async methods are always dumped in ContinueWith
            if (!callData.Trace || !LogWriter.IsLoggingEnabled() || methodReturn.IsAsyncCall())
            {
                return(methodReturn);
            }

            callData.ReturnValue  = methodReturn.ReturnValue;
            callData.OutputValues = methodReturn.Outputs;
            callData.Exception    = methodReturn.Exception;

            // if necessary wait for the async LogBeforeCall to finish
            if (callData.LogBeforeCall != null && !input.IsAsyncCall())
            {
                callData.LogBeforeCall.GetAwaiter().GetResult();
            }

            LogPostInvoke(input, callData).GetAwaiter().GetResult();

            return(methodReturn);
        }
Exemple #16
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result = getNext()(input, getNext);

            callsCompleted++;
            return(result);
        }
Exemple #17
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn retval = getNext()(input, getNext);

            retval.ReturnValue = valueToRewriteTo;
            return(retval);
        }
        /// <summary>
        /// The invoke.
        /// </summary>
        /// <param name="input">
        /// The input.
        /// </param>
        /// <param name="getNext">
        /// The get next.
        /// </param>
        /// <returns>
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (this.targetMethodReturnsVoid(input))
            {
                return(getNext()(input, getNext));
            }

            var inputs = new object[input.Inputs.Count];

            for (int i = 0; i < inputs.Length; ++i)
            {
                inputs[i] = input.Inputs[i];
            }

            string      cacheKey     = this.createCacheKey(input.MethodBase, inputs);
            ObjectCache cache        = MemoryCache.Default;
            var         cachedResult = (Object[])cache.Get(cacheKey);

            if (cachedResult == null)
            {
                IMethodReturn realReturn = getNext()(input, getNext);

                if (realReturn.Exception == null)
                {
                    this.addToCache(cacheKey, realReturn.ReturnValue);
                }

                return(realReturn);
            }

            IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult[0], input.Arguments);

            return(cachedReturn);
        }
Exemple #19
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (BookSqlSugarClient.Ado.Transaction != null)
            {
                IMethodReturn method = getNext()(input, getNext);

                if (method.Exception != null)
                {
                    return(input.CreateExceptionMethodReturn(method.Exception));
                }

                return(method);
            }

            BookSqlSugarClient.Ado.BeginTran();

            IMethodReturn methodReturn = getNext()(input, getNext);

            if (methodReturn.Exception != null)
            {
                BookSqlSugarClient.Ado.RollbackTran();

                return(input.CreateExceptionMethodReturn(methodReturn.Exception));
            }

            BookSqlSugarClient.Ado.CommitTran();

            return(methodReturn);
        }
Exemple #20
0
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>
        /// Return value from the target.
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            string name = Thread.CurrentPrincipal.Identity.Name;

            if (string.IsNullOrEmpty(name))
            {
                name = "unknown User";
            }

            string param = input.Arguments.Cast <object>().Aggregate("", (current, parameter) => current + (", " + parameter));

            if (param.Length > 0)
            {
                param = param.Substring(2);
            }

            Logger.Logger.Write(string.Format("{0}: Enter Method: {1}.{2}({3})", name, input.MethodBase.DeclaringType, input.MethodBase.Name, param), TraceEventType);

            IMethodReturn value = getNext()(input, getNext);

            value.InvokeAfterCall(input, d =>
            {
                if (d.Exception != null)
                {
                    Logger.Logger.Write(d.Exception);
                }

                Logger.Logger.Write(string.Format("{0}: Exit Method: {1}.{2}({3})", name, input.MethodBase.DeclaringType, input.MethodBase.Name, param), TraceEventType);
            });
            return(value);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn returnValue = null;

            //顺序执行
            returnValue = getNext()(input, getNext);

            //若符合要求
            if (input.MethodBase is MethodInfo && (input.MethodBase as MethodInfo).ReturnType == typeof(bool))
            {
                //根据异常状态设置返回值
                if (null != returnValue.Exception)
                {
                    returnValue.ReturnValue = true;
                }
                else
                {
                    returnValue.ReturnValue = false;
                }

                //设置返回值类型
                returnValue = CustomMethodReturn.PrepareCustomReturn(input, returnValue);
            }


            return(returnValue);
        }
        public IMethodReturn Invoke(
            IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                Console.WriteLine("ExceptionLoggerCallHandler:");
                Console.WriteLine("\tParameters:");
                for (int i = 0; i < input.Arguments.Count; i++)
                {
                    var parameter = input.Arguments[i];
                    Console.WriteLine(
                        string.Format("\t\tParam{0} -> {1}", i, parameter.ToString()));
                }
                Console.WriteLine();
                Console.WriteLine("Exception occured: ");
                Console.WriteLine(
                    string.Format("\tException -> {0}", result.Exception.Message));

                Console.WriteLine();
                Console.WriteLine("StackTrace:");
                Console.WriteLine(Environment.StackTrace);
            }

            return(result);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            WriteLog($"Invoking method {input.MethodBase} at {DateTime.Now.ToLongTimeString()}");

            IMethodReturn result = getNext()(input, getNext);

            WriteLog($"Method {input.MethodBase} {(result.Exception != null ? $"threw exception {result.Exception.Message}" : $"returns {result.ReturnValue}")} at {DateTime.Now.ToLongTimeString()}");
Exemple #24
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (Key.IsEmpty())
            {
                Key = input.Arguments.EnumerableItemToMd5();
            }
            // MemcachedCached.Instance.Get<object>(Key, CachedNodeName);
            Console.WriteLine("开始拦截...");
            var returnVal = new object();

            returnVal = null;
            if (returnVal == null)
            {
                try
                {
                    //MemcachedCached.Instance.AsyncStore(Key, tmpReturnVal.ReturnValue, TimeOut, CachedNodeName);
                    tmpReturnVal = getNext()(input, getNext);
                    return(tmpReturnVal);
                }
                finally
                {
                }
            }
            else
            {
                var arguments = new object[input.Arguments.Count];
                input.Arguments.CopyTo(arguments, 0);
                return(new VirtualMethodReturn(input, returnVal, arguments));
            }
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            MethodInfo targetMethod = (MethodInfo)input.MethodBase;

            if (targetMethod.ReturnType == typeof(void))
            {
                return(getNext()(input, getNext));
            }
            object[] inputs = new object[input.Inputs.Count];
            input.Inputs.CopyTo(inputs, 0);
            string cacheKey = CacheKeyGenerator(targetMethod, inputs);

            object[] cachedResult = HttpRuntime.Cache.Get(cacheKey) as object[];
            if (null == cachedResult)
            {
                IMethodReturn realReturn = getNext()(input, getNext);
                if (null == realReturn.Exception)
                {
                    HttpRuntime.Cache.Insert(
                        cacheKey,
                        new object[] { realReturn.ReturnValue },
                        null,
                        DateTime.Now.Add(this.ExpirationTime),
                        Cache.NoSlidingExpiration);
                }
                return(realReturn);
            }

            return(input.CreateMethodReturn(cachedResult[0], new object[] { input.Arguments }));
        }
Exemple #26
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input.Arguments.Count > 0)
            {
                var arguments = new Argument[input.Arguments.Count];

                for (int i = 0; i < input.Arguments.Count; i++)
                {
                    arguments[i] = new Argument
                    {
                        Name  = input.Arguments.ParameterName(i),
                        Value = input.Arguments[i]
                    };
                }

                _tape.RecordRequest(arguments, input.MethodBase.ReflectedType, input.MethodBase.Name);
            }

            Console.WriteLine("> Intercepting " + input.MethodBase.Name);
            Console.WriteLine("> Intercepting " + input.MethodBase.ReflectedType);

            IMethodReturn methodReturn = getNext()(input, getNext);

            Console.WriteLine("> Intercepted return value: " + methodReturn.ReturnValue.GetType().Name);

            if (methodReturn.ReturnValue != null)
            {
                _tape.RecordResponse(methodReturn.ReturnValue, input.MethodBase.ReflectedType, input.MethodBase.Name);
            }

            return(methodReturn);
        }
Exemple #27
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn methodReturn = getNext()(input, getNext);

            Console.WriteLine("最后发个短信通知");
            return(methodReturn);
        }
Exemple #28
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            /* Call the method that was intercepted */
            string className  = input.MethodBase.DeclaringType.Name;
            string methodName = input.MethodBase.Name;
            string generic    = input.MethodBase.DeclaringType.IsGenericType ? string.Format("<{0}>", input.MethodBase.DeclaringType.GetGenericArguments().ToStringList()) : string.Empty;
            string arguments  = input.Arguments.ToStringList();

            string preMethodMessage = string.Format("{0}{1}.{2}({3})", className, generic, methodName, arguments);

            log.Debug("PreMethodCalling: " + preMethodMessage);
            //Logging
            log.Debug(preMethodMessage);
            //Invoke method
            IMethodReturn msg = null;

            msg = getNext()(input, getNext);
            //loggin exception
            if (msg.Exception != null)
            {
                log.Error(msg.Exception);
            }

            //Post method calling
            string postMethodMessage = string.Format("{0}{1}.{2}() -> {3}", className, generic, methodName, msg.ReturnValue);

            log.Debug("PostMethodCalling: " + postMethodMessage);
            //Logging
            log.Debug(postMethodMessage);
            return(msg);
        }
Exemple #29
0
 /// <summary>
 /// Invokes the after call action. This method handles the async methods as well.
 /// If the method returns <see cref="Task"/> or the generic version the action will be called after the task has been completed.
 /// </summary>
 /// <param name="input">Inputs to the current call to the target.</param>
 /// <param name="afterCall">The action to call after the current method executed.</param>
 /// <param name="methodReturn">The computed method return.</param>
 /// <returns>The original method return.</returns>
 public static IMethodReturn InvokeAfterCall(this IMethodReturn methodReturn, IMethodInvocation input, Action <IMethodReturn> afterCall)
 {
     if (afterCall != null)
     {
         var returnType = (input.MethodBase as MethodInfo).ReturnType;
         if (returnType == typeof(Task) || (returnType.IsGenericType && returnType.BaseType == typeof(Task)))
         {
             (methodReturn.ReturnValue as Task).ContinueWith((task) =>
             {
                 IMethodReturn asyncResult;
                 if (task.Exception != null)
                 {
                     asyncResult = input.CreateExceptionMethodReturn(task.Exception);
                 }
                 else
                 {
                     object taskReturnValue = null;
                     if (returnType.IsGenericType)
                     {
                         taskReturnValue = (task as dynamic).Result;
                     }
                     asyncResult = input.CreateMethodReturn(taskReturnValue);
                 }
                 afterCall.Invoke(asyncResult);
             });
         }
         else
         {
             afterCall.Invoke(methodReturn);
         }
     }
     return(methodReturn);
 }
        public IMethodReturn Invoke(IMethodInvocation input,
                                    GetNextInterceptionBehaviorDelegate getNext)
        {
            var cacheKey = BuildCacheKey(input);

            if (_action == CachingAction.Add)
            {
                // If cache is empty, execute the target method, retrieve the return value and cache it.
                if (!_cache.Any(k => k.Key == cacheKey))
                {
                    // Execute the target method
                    IMethodReturn returnVal = getNext()(input, getNext);
                    // Cache the return value
                    _cache.Add(cacheKey, returnVal.ReturnValue, GetExpiration());

                    return(returnVal);
                }

                // Otherwise, return the cache result
                return(input.CreateMethodReturn(_cache.Get(cacheKey), input.Arguments));
            }
            else
            {
                _cache.Remove(cacheKey);

                IMethodReturn returnVal = getNext()(input, getNext);
                return(returnVal);
            }
        }
        private IMethodReturn loadUsingCache()
        {
            //We need to synchronize calls to the CacheHandler on method level
            //to prevent duplicate calls to methods that could be cached.
            lock (input.MethodBase)
            {
                if (TargetMethodReturnsVoid(input))
                {
                    return(getNext()(input, getNext));
                }

                var inputs = new object[input.Inputs.Count];
                for (int i = 0; i < inputs.Length; ++i)
                {
                    inputs[i] = input.Inputs[i];
                }
                string cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs);

                IMethodReturn returnResult = null;

                returnResult = TryToInvoke(cacheKey, returnResult);

                return(returnResult);
            }
        }
 private static Task TryGetAsyncReturnTask(IMethodInvocation input, IMethodReturn result)
 {
     var taskResult = result.ReturnValue as Task;
     var isAsync = taskResult != null &&
                   GetExecutingMethod(input).GetCustomAttributes(asyncStateMachineAttribute, true)
                                            .Any();
     return isAsync ? taskResult : null;
 }
 private static string CreateMethodReturnMessage(string formattedInvocation, IMethodReturn result, Stopwatch stopwatch)
 {
     return string.Format(
         CultureInfo.InvariantCulture,
         "{0} -> {1} [{2} ms]",
         formattedInvocation,
         FormatMethodReturn(result),
         stopwatch.ElapsedMilliseconds
     );
 }
        public static IActionReturn ApplyMethodReturn(this IActionReturn @this, IMethodReturn res)
        {
            if (res != null)
            {
                if (res.Exception != null)
                {
                    @this.Exception = res.Exception;
                }
                else
                {
                    @this.Value = res.ReturnValue;

                    for (var i = 0; i < res.Outputs.Count; i++)
                        @this.Outputs[i].Value = res.Outputs[i];
                }

            }

            return @this;
        }
        public static IMethodReturn ToMethodReturn(this IActionReturn @this, IMethodReturn res, IMethodInvocation original)
        {
            if (res != null)
            {
                if (@this.Exception != null)
                {
                    res.Exception = @this.Exception;
                }
                else
                {
                    res.ReturnValue = @this.Value;

                    for (var i = 0; i < @this.Outputs.Count; i++)
                        res.Outputs[i] = @this.Outputs[i].Value;
                }
                return res;
            }
            else
            {
                return (@this.Exception != null)
                           ? new VirtualMethodReturn(original, @this.Exception)
                           : new VirtualMethodReturn(original, @this.Value, @this.Outputs.Select(x => x.Value).ToArray());
            }
        }
        private static string FormatMethodReturn(IMethodReturn methodReturn)
        {
            if (methodReturn.Exception != null) {
                return "threw exception "
                    + FormatForLog(methodReturn.Exception)
                    + ": "
                    + methodReturn.Exception.Message
                    + Environment.NewLine
                    + methodReturn.Exception.StackTrace;
            }

            return FormatForLog(methodReturn.ReturnValue);
        }
 private void Log(IMethodInvocation input, IMethodReturn methodReturn)
 {
     var auditLogger = AuditLogger.CreateAuditLogger(FunctionName);
     auditLogger.Write(input.MethodBase.Name, string.Empty,
        JsonConvert.SerializeObject(input.Arguments),
        JsonConvert.SerializeObject(methodReturn.ReturnValue));
     auditLogger.Flush();
 }
Exemple #38
0
        private void WriteCompleteLogEntryToLogger(string className, string methodName, IMethodReturn methodReturn)
        {
            string logMessage;

            logMessage = string.Format(
                "Complete on object {0} method {1} with following result: {2}", className, methodName, methodReturn.ReturnValue);

            this.logger.Log(logMessage);

            Debug.WriteLine(logMessage);
        }
        private void LogPostCall(IMethodInvocation input, IMethodReturn result, Stopwatch stopwatch, Nullable<long> tracingStartTicks)
        {
            //if (logAfterCall)
            {
                MonitoringPopulateLogEntry utility = new MonitoringPopulateLogEntry();

                if (FunctionId != null)
                {
                    AppContext.Current.FunctionID = FunctionId;
                }

                if (ModuleId != null)
                {
                    AppContext.Current.ModuleID = ModuleId;
                }

                utility.PopulateLogEntryForCallHandler(input,
                    //categories,
                    //includeParameters, includeCallStack,
                    result,
                    tracingStartTicks,
                    Stopwatch.GetTimestamp(),
                    (stopwatch==null)?0:stopwatch.ElapsedMilliseconds,
                    Resources.EndTrace,
                    AppContext.Current.ModuleID,
                    AppContext.Current.FunctionID,
                    Component);

            }
        }
        public void PopulateLogEntryForCallHandler(IMethodInvocation input, 
            //List<string> categories,
            //bool includeParameters, bool includeCallStack,
            IMethodReturn result,
            long? tracingStartTicks, long? tracingEndTicks,
            long elapsedMilliseconds,
            string messageFormat,
            string moduleId,
            string functionId,
            ComponentType component)
        {
            MonitoringLogEntry logEntry = PopulateDefaultLogEntry();

            using (BackgroundWorker worker = new BackgroundWorker())
            {

                worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                {
                    try
                    {
                        AppContext.SetToCallContext(AppContext.Current.ToDictionary());
                        CategoryFormatter formatter = new CategoryFormatter(input.MethodBase);
                        logEntry = eDoWork.Argument as MonitoringLogEntry;
                        //foreach (string category in categories)
                        //{
                        //    logEntry.Categories.Add(formatter.FormatCategory(category));
                        //}
                        logEntry.Categories.Add(formatter.FormatCategory(LoggingCategories.Monitoring));

                        logEntry.Component = component;

                        if (!Logger.ShouldLog(logEntry))
                        {
                            return;
                        }

                        //When do the instrumentation log , we should log the parameter values information, otherwise not
                        if ((logEntry.Flag & FilterFlag.InstrumentationFlag) == FilterFlag.InstrumentationFlag)
                        {
                            //if (includeParameters)
                            {
                                logEntry.ParameterValues = GenerateValuesInfo(input.Arguments, true);
                            }
                        }

                        //if (includeCallStack)
                        //{
                        //    logEntry.CallStack = Environment.StackTrace;
                        //}

                        logEntry.TypeName = input.Target.GetType().FullName;

                        logEntry.MethodName = string.Concat(input.MethodBase.DeclaringType.FullName, ".", input.MethodBase.Name);

                        if (result == null)
                        {
                            PopulatePreLogEntry(logEntry);
                        }
                        else
                        {
                            PopulatePostLogEntry(logEntry);
                            if ((logEntry.Flag & FilterFlag.InstrumentationFlag) == FilterFlag.InstrumentationFlag)
                            {
                                int depth = 0;
                                object returnedValue = result.ReturnValue;
                                logEntry.ReturnValue = GenerateValueInfo("ReturnValue", returnedValue, (returnedValue == null) ? null : returnedValue.GetType(), ref depth);
                            }
                        }

                        logEntry.TracingStartTicks = tracingStartTicks;
                        logEntry.TracingEndTicks = tracingEndTicks;
                        logEntry.SecondsElapsed = GetSecondsElapsed(elapsedMilliseconds);
                        logEntry.Message = string.Format(Resources.Culture, messageFormat,
                                    logEntry.ExtendedActivityId,
                                    logEntry.MethodName,
                                    logEntry.TracingEndTicks,
                                    logEntry.SecondsElapsed);

                        logEntry.FunctionId = functionId;

                        logEntry.ModuleId = moduleId;

                        //if (result.ReturnValue != null && includeParameters)
                        //{
                        //    logEntry.ReturnValue = result.ReturnValue.ToString();
                        //}
                        if (result != null && result.Exception != null)
                        {
                            logEntry.Exception = result.Exception.ToString();
                        }

                        LogWriter logWriter = Logger.Writer;
                        logWriter.Write(logEntry);

                    }
                    catch (Exception ex)
                    {
                        //Swallow exception, because it is logging should not impact the business function
                        HiiPLoggingExceptionHandler handler = new HiiPLoggingExceptionHandler("Server Exception",
                            100, TraceEventType.Error,
                            "Instrumtation logging of RowUpdated failed",
                            0,
                            typeof(HiiPLoggingExceptionFormatter),
                            ComponentType.StoredProcedure,
                            Logger.Writer);
                        handler.HandleException(ex, Guid.NewGuid());
                    }

                };

                worker.RunWorkerAsync(logEntry);
            }
        }
        private void LogReturn(IMethodInvocation input, IMethodReturn methodReturn)
        {
            var loggerContextInfo = new LoggerContextInfo
            {
                ObjectType = input.Target.GetType(),
                MethodName = input.MethodBase.Name
            };

            var outputs = JsonConvert.SerializeObject(methodReturn.Outputs);
            var serializedArguments = JsonConvert.SerializeObject(GetArgs(input));
            var sessionToken = string.Empty;
            if (HttpContext.Current != null)
            {
                // Use Session?
            }
            // we can make logging faster to not-fire if we move this up to the top
            if (methodReturn.Exception == null)
            {
                if (!ShouldLog) return;
                var logProvider = ServiceLocator.Current.GetInstance<ILogProvider>();
                logProvider.LogInfo(string.Format("Session {0}: Successfully finished {1} with [{2}] - Returned {3} AND Outputs {4}", sessionToken, input.MethodBase, serializedArguments, methodReturn.ReturnValue, outputs), loggerContextInfo);
            }
            else
            {
                var logMessage = "No Message";
                if (methodReturn.Exception.Data.Contains("HasBeenLogged"))
                {
                    logMessage =
                        string.Format(
                            "Session {0}: Finished {1} with [{2}] - Having Previously Logged Exception {3} with Message {4} AND Outputs {5}",
                            sessionToken, input.MethodBase, serializedArguments, methodReturn.Exception.GetType().Name,
                            methodReturn.Exception.Message, outputs);
                }
                else
                {
                    try
                    {
                        methodReturn.Exception.Data.Add("HasBeenLogged", true);
                    }
                    catch (ArgumentException)
                    {
                        // what are we going to do here?
                    }
                    logMessage =
                        string.Format(
                            "Session {0}: Finished {1} with [{2}] - Having Exception {3} with Message - (StackTrace) {4} - ({5})  AND Outputs {6}",
                            sessionToken, input.MethodBase, serializedArguments, methodReturn.Exception.GetType().Name,
                            methodReturn.Exception.Message, methodReturn.Exception.StackTrace, outputs);

                }
                var logProvider = ServiceLocator.Current.GetInstance<ILogProvider>();
                logProvider.LogError(logMessage, loggerContextInfo);
            }
        }
        private object GetResultValue(IMethodReturn methodReturn)
        {
            LambdaExpression parameterTypeMap;

            if (methodReturn.ReturnValue != null && _propertyMappingDictionary.TryGetValue(methodReturn.ReturnValue.GetType(), out parameterTypeMap))
            {
                return parameterTypeMap.Compile().DynamicInvoke(methodReturn.ReturnValue);
            }

            return methodReturn.ReturnValue;
        }
Exemple #43
0
        private void LogPostCall(IMethodInvocation input, Stopwatch sw, IMethodReturn result)
        {
            if (logAfterCall)
            {
                TraceMsgEntry MsgEntry = GetLogEntry(input);
                MsgEntry.Message = afterMessage;
                MsgEntry.ReturnValue = null;

                if (result.ReturnValue != null && includeParameters)
                {
                    MsgEntry.ReturnValue = result.ReturnValue.ToString();
                }
                if (result.Exception != null)
                {
                    MsgEntry.Exception = result.Exception.ToString();
                }
                if (includeCallTime)
                {
                    MsgEntry.CallTime = sw.Elapsed;
                }
                logWriter.Write(MsgEntry);
            }
        }