public override void OnInvoke(MethodInterceptionArgs args)
        {
            //cache manager türetiliyor
            var cacheManager = new MemoryCacheManager();

            //metod ismi alınıyor
            var methodName = string.Format("{0}.{1}.{2}",
                                           args.Method.ReflectedType.Namespace,
                                           args.Method.ReflectedType.Name,
                                           args.Method.Name);

            //metod parametreleri alınıyor
            var arguments = args.Arguments.ToList();

            //cache key oluşturuluyor {MetodAdı.Parametreler}
            var key = string.Format("{0}({1})", methodName, string.Join(",", arguments.Select(x => x != null ? x.ToString() : "<Null>")));

            //metod cache de var ise oradan çağrılıyor
            if (cacheManager.IsAdd(key))
            {
                args.ReturnValue = cacheManager.Get <object>(key);
                return;
            }

            //metod çalıştırılıyor
            base.OnInvoke(args);

            //metod cache ekleniyor
            cacheManager.Add(key, args.ReturnValue, _dakika);
        }
        public static void EnsureIsStarted(Key key,
                                           ICacheItemRecalculationStrategy recalculationStrategy,
                                           MethodInterceptionArgs args,
                                           ICache cache)
        {
            var keyString = key.ToString();
            Ensure.That<NHelpfulException.FrameworkExceptions.ArgumentException>(keyString.Length.IsLessThanOrEqualTo(260),
                                                              "key must be less than 260 characters long.");

            try
            {
                bool createdNew;
                var mutex = new Mutex(false, MutexPrefix + keyString, out createdNew);
                if (createdNew)
                {
                    if (cache[keyString].IsNotNull())
                        return;
                    //item already in cache, assume thread already started TODO: possibly log this as an error

                    ThreadPool.QueueUserWorkItem(
                        o => recalculationStrategy.RunRoutine(key, args, cache, mutex, args.Proceed));

                    //NOTE: mutex.ReleaseMutex(); is not called because the mutex is only expected to be released upon closure of the application
                }
            }
            catch (Exception)
            {
                //log exception
                throw;
            }
        }
        public override void OnInvoke(MethodInterceptionArgs eventArgs)
        {
            DispatcherObject dispatcherObject = (DispatcherObject)(eventArgs.Instance ?? eventArgs.Arguments.GetArgument(0));


            if (dispatcherObject == null || dispatcherObject.CheckAccess())
            {
                // We are already in the GUI thread. Proceed.
                eventArgs.Proceed();
            }
            else
            {
                if (this.Async)
                {
                    // Invoke the target method asynchronously (don't wait).
                    dispatcherObject.Dispatcher.BeginInvoke(this.Priority,
                                                            new Action(eventArgs.Proceed));
                }
                else
                {
                    // Invoke the target method synchronously.
                    dispatcherObject.Dispatcher.Invoke(
                        this.Priority,
                        new Action(eventArgs.Proceed));
                }
            }
        }
        private static readonly ManualResetEvent ZeroPendingInvokes = new ManualResetEvent(true); //true/signalled if there are no invokes pending

        public override sealed void OnInvoke(MethodInterceptionArgs args)
        {
            var synchronizeObject = InvokeRequiredInfo.SynchronizeObject ?? args.Instance as ISynchronizeInvoke;

            if (synchronizeObject == null || !synchronizeObject.InvokeRequired)
            {
                args.Proceed();
            }
            else
            {
                lock (InvokeLock)
                {
                    try
                    {
                        if (Interlocked.Increment(ref pendingInvokes) > 0)
                        {
                            ZeroPendingInvokes.Reset();
                        }
                        synchronizeObject.Invoke(new Action(args.Proceed), new object[0]);
                    }
                    catch (ObjectDisposedException e)
                    {
                        LogInvokeError(args.Method.Name, e, false);
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref pendingInvokes) == 0)
                        {
                            ZeroPendingInvokes.Set();
                        }
                    }
                }
            }
        }
Example #5
0
        private Dictionary <string, object> GetKeyValues(MethodInterceptionArgs args, object resultsFromInner, object[] parameterValues)
        {
            var converter = createDataKeyConverter.Invoke(new object[0]);

            var classNameNonGeneric = !this.isClassGeneric
                ? this.className
                : args.Method.DeclaringType.FullName;

            var parameterTypeNamesNonGeneric = !this.isMethodGeneric
                ? this.parameterTypeNames
                : args.Method.GetParameters().Select(p => p.ParameterType.FullName).ToArray();

            Dictionary <string, object> values = new Dictionary <string, object>();

            foreach (object result in resultsFromInner as IEnumerable)
            {
                var k = convertDataToKey.Invoke(converter, new[] { result });

                var keyList = this.createKeyList.Invoke(new object[0]);
                this.addKey.Invoke(keyList, new[] { k });
                parameterValues[this.keyParameterNumber] = keyList;

                var key = new CacheKey(classNameNonGeneric, this.methodName, parameterTypeNamesNonGeneric, parameterValues, genericArgumentTypeNames)
                          .ToString();
                values[key] = result;
            }

            return(values);
        }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var aggregateExceptions = new List <Exception>();
            var retries             = 0;

            while (retries++ < this._maxRetries)
            {
                try
                {
                    Console.WriteLine();
                    Console.WriteLine("starting transaction...");
                    using (var scope = new TransactionScope())
                    {
                        Console.WriteLine("transaction started...");
                        Console.WriteLine("start invoking method from aspect...");
                        args.Proceed();
                        Console.WriteLine("method invokation done...");
                        scope.Complete();
                        Console.WriteLine("scope completed...");
                    }

                    break;
                }
                catch (Exception ex)
                {
                    aggregateExceptions.Add(ex);
                    if (retries >= this._maxRetries)
                    {
                        throw new AggregateException($"Trasaction failed after {this._maxRetries} attempts", aggregateExceptions);
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(this._retryDelay));
                }
            }
        }
        /// <summary>
        ///    Method invoked <i>instead</i> of the original method.
        /// </summary>
        /// <param name="args">Method invocation context.</param>
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            for (var retryIndex = 0;; retryIndex++)
            {
                try
                {
                    // Invoke the intercepted method
                    args.Proceed();

                    // If we get here, it means the execution was successful.
                    return;
                }
                catch (Exception e) when(ExceptionTypeFilter(e))
                {
                    // The intercepted method threw an exception. Figure out if we can retry the method.
                    if (retryIndex < MaxRetries)
                    {
                        // Yes, we can retry. Write some message and wait a bit.

                        Console.WriteLine(
                            "Method failed with exception {0}. Sleeping {1} s and retrying. This was our {2}th attempt.",
                            e.GetType().Namespace, Delay, retryIndex + 1);

                        Thread.Sleep(TimeSpan.FromSeconds(Delay));

                        // Continue to the next iteration.
                    }
                    else
                    {
                        // No, we cannot retry. Retry the exception.
                        throw;
                    }
                }
            }
        }
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			using ( source()( args.Method ) )
			{
				base.OnInvoke( args );
			}
		}
        /// <summary>
        /// Method invoked <i>instead</i> of the method to which the aspect has been applied.
        /// </summary>
        /// <param name="args">Advice arguments.</param>
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            IExecuteActionStrategy strategy = null;

            if (CustomStrategy != null)
            {
                strategy = ExecuteActionStrategy.GetSingleton(CustomStrategy);
            }
            else if (_strategy != null)
            {
                switch (_strategy.Value)
                {
                case StandardExecutionStrategy.HandleReprocessableException:
                    strategy = ExecuteActionStrategy.HandleReprocessableException;
                    break;

                case StandardExecutionStrategy.NoReprocess:
                    strategy = ExecuteActionStrategy.NoReprocess;
                    break;

                case StandardExecutionStrategy.HandleUniqueConstraintViolation:
                    strategy = ExecuteActionStrategy.HandleUniqueConstraintViolation;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            GetDomain().ExecuteInternal(IsolationLevel, _transactionOpenMode, strategy, session => args.Proceed());
        }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     LoggingHelper.Writelog("Starting transaction");
     using (var scope = new TransactionScope())
     {
         var retries = 3;
         var succeeded = false;
         while (!succeeded)
         {
             try
             {
                 args.Proceed();//包含了被调用方法传递过来的参数了
                 scope.Complete();
                 succeeded = true;
             }
             catch
             {
                 if (retries >= 0)
                     retries--;
                 else
                     throw;
             }
         }
     }
     LoggingHelper.Writelog("Transaction complete");
 }
        public override void OnInvoke( MethodInterceptionArgs eventArgs )
        {
            DispatcherObject dispatcherObject = (DispatcherObject) (eventArgs.Instance ?? eventArgs.Arguments.GetArgument( 0 ));

            if ( dispatcherObject == null || dispatcherObject.CheckAccess() )
            {
                // We are already in the GUI thread. Proceed.
                eventArgs.Proceed();
            }
            else
            {
                if ( this.Async )
                {
                    // Invoke the target method asynchronously (don't wait).
                    dispatcherObject.Dispatcher.BeginInvoke( this.Priority,
                                                             new Action( eventArgs.Proceed ) );
                }
                else
                {
                    // Invoke the target method synchronously.
                    dispatcherObject.Dispatcher.Invoke(
                        this.Priority,
                        new Action( eventArgs.Proceed ) );
                }
            }
        }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var methodName = string.Format("{0}.{1}.{2}"
                                           , args.Method.ReflectedType.Namespace
                                           , args.Method.ReflectedType.Name
                                           , args.Method.Name);
            var arguments = args.Arguments.ToList();
            var key       = string.Format("{0}({1})"
                                          , methodName
                                          , string.Join(",", arguments.Select(x => x != null ? x.ToString() :"<Null>")));

            if (_cacheManager.IsAdd(key))
            {
                args.ReturnValue = _cacheManager.Get <object>(key);
            }
            base.OnInvoke(args);
            _cacheManager.Add(key, args.ReturnValue, _cacheByMinute);

            //böylede yazılabilir sanırım

            /*
             *  if (_cacheManager.IsAdd(key))
             *  {
             *      args.ReturnValue = _cacheManager.Get<object>(key);
             *      base.OnInvoke(args);
             *  }
             *  else
             *  {
             *      base.OnInvoke(args);
             *      _cacheManager.Add(key, args.ReturnValue, _cacheByMinute);
             *  }
             */
        }
        public override async Task OnInvokeAsync(MethodInterceptionArgs args)
        {
            if (args.Instance is ICacheAware cacheAware && !cacheAware.CacheEnabled)
            {
                await args.ProceedAsync();

                return;
            }

            var key = GetKey(args.Method as MethodInfo, args.Arguments);

            using (var connection = ConnectionMultiplexer.Connect(redisServer.Value))
            {
                var db         = connection.GetDatabase();
                var redisValue = await db.StringGetAsync(key);

                if (redisValue.IsNullOrEmpty)
                {
                    await args.ProceedAsync();

                    db.StringSet(key, JsonConvert.SerializeObject(args.ReturnValue), Expiry);
                }
                else
                {
                    args.ReturnValue = JsonConvert.DeserializeObject(redisValue.ToString(), (args.Method as MethodInfo).ReturnType.GenericTypeArguments[0]);
                }
            }
        }
Example #14
0
        public sealed override void OnInvoke(MethodInterceptionArgs args)
        {
            if (Interlocked.Read(ref initialized) == 0L)
            {
                this.cache = CacheManager.GetCache(this.cacheName);
                Interlocked.Exchange(ref initialized, 1L);
            }

            var cacheToUse = this.cache;

            if (cacheToUse == null)
            {
                base.OnInvoke(args);
                return;
            }

            var classNameNonGeneric = !this.isClassGeneric
                ? this.className
                : args.Method.DeclaringType.FullName;

            var parameterTypeNamesNonGeneric = !this.isMethodGeneric
                ? this.parameterTypeNames
                : args.Method.GetParameters().Select(p => p.ParameterType.FullName).ToArray();

            var parameterValues = args.Arguments.Where((arg, index) => !this.indexesNotToCache.Contains(index)).ToArray();

            var key = new CacheKey(classNameNonGeneric, this.methodName, parameterTypeNamesNonGeneric, parameterValues).ToString();

            args.ReturnValue = cacheToUse.Get <object>(key, () => { base.OnInvoke(args); return(args.ReturnValue); });
        }
Example #15
0
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     var thread = new Thread(args.Proceed);
     thread.Start();
     //var task = new Task(args.Proceed);
     //task.Start();
 }
Example #16
0
        public override void OnInvoke( MethodInterceptionArgs eventArgs )
        {
            // Compute the cache key.
            string key = this.formatStrings.Format( eventArgs.Instance,
                         eventArgs.Method,
                         eventArgs.Arguments.ToArray() );

            object value;

            if ( !cache.TryGetValue( key, out value ) )
            {
                lock ( this )
                {
                    if ( !cache.TryGetValue( key, out value ) )
                    {
                        eventArgs.Proceed();
                        value = eventArgs.ReturnValue;
                        cache.Add( key, value );
                        return;
                    }
                }
            }

            eventArgs.ReturnValue = value;
        }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var key = GenerateKey(args);
            MemoryCache cache = CacheManager.GetCache(this.CacheName);
            object cachedValue = cache.Get(key);

            if (cachedValue != null)
            {
                args.ReturnValue = cachedValue;
            }
            else
            {
                lock (syncRoot)
                {
                    if (cachedValue == null)
                    {
                        var returnVal = args.Invoke(args.Arguments);
                        args.ReturnValue = returnVal;

                        if (returnVal != null)
                        {
                            CacheItemPolicy policy = new CacheItemPolicy();
                            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(TimeoutSeconds);

                            cache.Add(key, returnVal, policy);
                        }
                    }
                    else
                    {
                        args.ReturnValue = cachedValue;
                    }
                }
            }
        }
Example #18
0
            // intercept the method invocation
            public override void OnInvoke(MethodInterceptionArgs eventArgs)
            {
                // get the arguments that were passed to the method
                object[] args = eventArgs.Arguments.ToArray();

                // start building a key based on the method name
                // because it wouldn't help to return the same value
                // every time "lulu" was passed to any method
                StringBuilder keyBuilder = new StringBuilder(eventArgs.Method.Name);

                // append the hashcode of each arg to the key
                // this limits us to value types (and strings)
                // i need a better way to do this (and preferably
                // a faster one)
                for (int i = 0; i < args.Length; i++)
                {
                    keyBuilder.Append(args[i].GetHashCode());
                }

                string key = keyBuilder.ToString();

                // if the key doesn't exist, invoke the original method
                // passing the original arguments and store the result
                if (!memos.ContainsKey(key))
                {
                    memos[key] = eventArgs.Invoke(eventArgs.Arguments);
                }

                // return the memo
                eventArgs.ReturnValue = memos[key];
            }
        private static readonly ManualResetEvent ZeroPendingInvokes = new ManualResetEvent(true); //true/signalled if there are no invokes pending
        
        public override sealed void OnInvoke(MethodInterceptionArgs args)
        {
            var synchronizeObject = InvokeRequiredInfo.SynchronizeObject ?? args.Instance as ISynchronizeInvoke;

            if (synchronizeObject == null || !synchronizeObject.InvokeRequired)
            {
                args.Proceed();
            }
            else
            {
                lock (InvokeLock)
                {
                    try
                    {
                        if (Interlocked.Increment(ref pendingInvokes) > 0)
                        {
                            ZeroPendingInvokes.Reset();
                        }
                        synchronizeObject.Invoke(new Action(args.Proceed), new object[0]);
                    }
                    catch (ObjectDisposedException e)
                    {
                        LogInvokeError(args.Method.Name, e, false);
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref pendingInvokes) == 0)
                        {
                            ZeroPendingInvokes.Set();
                        }
                    }
                }
            }
        }
Example #20
0
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     args.Arguments[0] = defaultInputParameter;
     base.OnInvoke(args);
     //or you can use args.Proceed()
     args.SetReturnValue(defaultReturnParameter);
 }
Example #21
0
        /// <summary>
        /// Invoked when a target (assembly, class or method) contains a method which has been invoked.
        /// Arguments and return values are retrieved via reflection, making it inefficient, so this
        /// should not be applied in production code except when debugging. Any method parameters and
        /// return values are logged with <see cref="EventLogger"/>, which is thread-safe, so an event-id
        /// is written for each method invocation to easily be able to distinguish between events.
        /// </summary>
        /// <param name="args">The arguments of advices of aspect type <see cref="MethodInterceptionAspect"/>.</param>
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            MethodInfo methodInfo = args.Method as MethodInfo;

            if (methodInfo != null && args != null)
            {
                string loggerName = methodInfo.ReflectedType.FullName;

                Arguments arguments = args.Arguments;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                string eventID = Guid.NewGuid().ToString();

                for (int i = 0; i < args.Arguments.Count; i++)
                {
                    EventLogger.Log(loggerName, LogLevel.Trace, eventID, parameters[i] + " " + arguments[i]);
                }

                if (methodInfo.ReturnType != typeof(void))
                {
                    EventLogger.Log(loggerName, LogLevel.Trace, eventID, args.ReturnValue.GetType().FullName + " " +
                        args.ReturnValue == null ? "null" : args.ReturnValue.ToString());
                }
            }

            base.OnInvoke(args);
        }
Example #22
0
        /// <inheritdoc />
        public sealed override async Task OnInvokeAsync(MethodInterceptionArgs args)
        {
            if (this.cache == null)
            {
                this.cache = CacheManager.GetCache(this.cacheName);
                if (this.cache == null)
                {
                    LogManager.GetCurrentClassLogger().Warn($"AOP cache [{this.cacheName}] is not initialized, define NoCache if needed!");
                }
            }

            var cacheToUse = this.cache;

            if (!cacheToUse.IsUseable())
            {
                await base.OnInvokeAsync(args).ConfigureAwait(false);

                return;
            }

            var key    = GetCacheKey(args);
            var result = await cacheToUse
                         .GetAsync(key, async() =>
            {
                await base.OnInvokeAsync(args).ConfigureAwait(false);
                return(args.ReturnValue);
            })
                         .ConfigureAwait(false);

            var returnType = GetReturnType(args.Method);

            args.ReturnValue = SafeCasting.CastTo(returnType, result);
        }
Example #23
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            //var form =(Form) args.Instance;
            //if (form.InvokeRequired)
            //{
            //    form.Invoke(new Action(args.Proceed));
            //}
            //else
            //{
            //    args.Proceed();
            //}

            var form = args.Instance as Form;

            if (form == null)
            {
                args.Proceed();
            }
            if (form.InvokeRequired)
            {
                form.Invoke(new Action(args.Proceed));
            }
            else
            {
                args.Proceed();
            }
        }
Example #24
0
 public sealed override void OnInvoke(MethodInterceptionArgs args)
 {
     if (specification.IsSatisfiedBy(this))
     {
         base.OnInvoke(args);
     }
 }
Example #25
0
        public sealed override void OnInvoke(MethodInterceptionArgs args)
        {
            if (this.cache == null)
            {
                this.cache = CacheManager.GetCache(this.cacheName);
                if (this.cache == null)
                {
                    LogManager.GetCurrentClassLogger().Warn($"AOP cache [{this.cacheName}] is not initialized, define NoCache if needed!");
                }
            }

            var cacheToUse = this.cache;

            if (!cacheToUse.IsUseable())
            {
                base.OnInvoke(args);
                return;
            }

            var key        = GetCacheKey(args);
            var result     = cacheToUse.Get <object>(key, () => { base.OnInvoke(args); return(args.ReturnValue); });
            var returnType = GetReturnType(args.Method);

            args.ReturnValue = SafeCasting.CastTo(returnType, result);
        }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            Console.WriteLine("{0}方法开始:{1}", args.Method.Name, DateTime.Now);
            using (var ts = new TransactionScope())
            {
                var retries   = 3;//重试3次
                var succeeded = false;
                while (!succeeded)
                {
                    try
                    {
                        args.Proceed(); //继续执行拦截的方法
                        ts.Complete();  //事务完成
                        succeeded = true;
                    }

                    catch (Exception ex)
                    {
                        if (retries >= 0)
                        {
                            retries--;
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
            }
            Console.WriteLine("{0}方法结束:{1}", args.Method.Name, DateTime.Now);
        }
Example #27
0
        /// <inheritdoc />
        public override void Invoke(MethodInterceptionArgs args)
        {
            var arguments = args.Method.QuerySingleAttribute <NonNullableAttribute>(true)?.Arguments ?? new string[0];
            var names     = args.Method.GetParameters().Select(p => p.Name).ToArray();

            object argument(int i) => args.Arguments[i];

            for (var i = 0; i < args.Arguments.Count; i++)
            {
                if (!arguments.Any() || arguments.Contains(names[i]))
                {
                    // scalar check
                    if (null == argument(i))
                    {
                        throw new ArgumentNullException(names[i]);
                    }

                    // vector (array) check
                    if (argument(i) is Array items)
                    {
                        for (var m = 0; m < items.Length; m++)
                        {
                            if (null == items.GetValue(m))
                            {
                                throw new ArgumentNullException($"{names[i]}[{m}]");
                            }
                        }
                    }
                }
            }

            Next.Invoke(args);
        }
Example #28
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            Control c = null;

            if (args.Instance is Control)
            {
                c = (Control)args.Instance;
            }
            else if (args.Instance is ListViewItem)
            {
                c = ((ListViewItem)args.Instance).ListView;
            }
            else if (args.Instance is DataGridViewRow)
            {
                c = ((DataGridViewRow)args.Instance).DataGridView;
            }
            if (c.InvokeRequired)
            {
                c.BeginInvoke(new Action(args.Proceed));
            }
            else
            {
                args.Proceed();
            }
        }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            Console.WriteLine("Starting transaction");
            // start new transaction
            using (var scope = new TransactionScope())
            {
                // retry up to three times
                var retries = 3;
                var succeeded = false;
                while (!succeeded)
                {
                    try
                    {
                        args.Proceed();

                        // complete transaction
                        scope.Complete();
                        succeeded = true;
                    }
                    catch
                    {
                        // don't re-throw until the
                        // retry limit is reached
                        if (retries >= 0)
                            retries--;
                        else
                            throw;
                    }
                }
            }
            Console.WriteLine("Transaction complete");
        }
        public void Process(MethodInterceptionArgs args, ILogger log)
        {
            try
            {
                args.Proceed();
            }
            catch (DefaultException ex)
            {
                log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));

                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                var url = urlHelper.Action("OperationError", "Error", new { area = "" });
                url += "/" + ex.Message;
                var result = new RedirectResult(url);

                args.ReturnValue = result;
            }
            catch (Exception ex)
            {
                log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));

                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                var url = urlHelper.Action("Index", "Error", new { area = "" });

                var result = new RedirectResult(url);

                args.ReturnValue = result;
            }
        }
Example #31
0
        public override async Task OnInvokeAsync(MethodInterceptionArgs args)
        {
            args.Arguments[0] = defaultInputParameter;
            await args.ProceedAsync();

            //or you can use await base.OnInvokeAsync(args);
            args.SetReturnValue(defaultReturnParameter);
        }
Example #32
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var someTest = args.Arguments[0] as SomeTestClass;

            someTest.Property      = 20;
            someTest.OtherProperty = 20;
            args.SetReturnValue(someTest.Property * someTest.OtherProperty);
        }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     try
     {
         args.Proceed();
     }
     catch (Exception) { }
 }
Example #34
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var inputArg = args.Arguments.First();

            args.Arguments[0] = defaultInputParameter;
            base.OnInvoke(args);
            //or you can use args.Proceed()
        }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     try
     {
         args.Proceed();
     }
     catch (Exception) { }
 }
Example #36
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var thread = new Thread(args.Proceed);

            thread.Start();
            //var task = new Task(args.Proceed);
            //task.Start();
        }
Example #37
0
        string BuildCacheKey(MethodInterceptionArgs args)
        {
            // this still isn't generic:  $"{form.Make}-{form.Model}-{form.Year}";

            var jsonBasedKey = JsonConvert.SerializeObject(args.Arguments) + "_PS";

            return(jsonBasedKey);
        }
Example #38
0
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     var form = (Form) args.Instance;
     if (form.InvokeRequired)
         form.Invoke(new Action(args.Proceed));
     else
         args.Proceed();
 }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     if (ThreadingService == null)
     {
         ThreadingService = new ThreadingService();
     }
     ThreadingService.QueueUserWorkItem(d => args.Invoke(args.Arguments));
 }
Example #40
0
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     foreach (int p in this.encodedParams)
     {
         args.Arguments.SetArgument(p, "encoded value");
     }
     args.Proceed();
 }
Example #41
0
            public override void OnInvoke(MethodInterceptionArgs args)
            {
                var target = (SomeClass)args.Instance;

                target.SomeFunction();

                args.Proceed();     // performs the method it applied to
            }
        /// <inheritdoc />
        public override void OnInvoke( MethodInterceptionArgs args )
        {
            TaskCreationOptions options = TaskCreationOptions.None;
            if ( this.IsLongRunning ) options |= TaskCreationOptions.LongRunning;

            Task task = new Task( args.Proceed, options );
            task.Start();
        }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     Stopwatch sw=new Stopwatch();
     sw.Start();
     base.OnInvoke(args);
     sw.Stop();
     logger.Trace("Method [{0}{1}] took [{2}] milliseconds to execute", args.Method?.DeclaringType?.Name ?? string.Empty, args.Method?.Name ?? string.Empty,
         sw.ElapsedMilliseconds);
 }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     base.OnInvoke(args);
     if (args.ReturnValue == null)
     {
         Console.WriteLine(
             "OMG, thing was null!!!!");
     }
 }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     DateTime startTime = DateTime.Now;
     args.Proceed();
     long duration = (DateTime.Now.Ticks - startTime.Ticks) / 10000;
     // give info only the process that takes more than 200 msec 
     if (duration > 200)
         mLogger.Info("{0}->{1} proceeded in {2} msec.", args.Instance, args.Method, duration);
 }
        /// <summary>
        /// Method invoked <i>instead</i> of the method to which the aspect has been applied.
        /// </summary>
        /// <param name="args">Advice arguments.</param>
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            args.Proceed();

            if (args.Instance is IService)
            {
                (args.Instance as IService).Transaction.Commit();
            }
        }
Example #47
0
        public override async Task OnInvokeAsync(MethodInterceptionArgs args)
        {
            var inputArg = args.Arguments.First();

            args.Arguments[0] = defaultInputParameter;
            await args.ProceedAsync();

            //or you can use await base.OnInvokeAsync(args);
        }
Example #48
0
            public CacheKey(MethodInterceptionArgs args)
            {
                //note this is a terrible example, we should be creating an array
                //of arguments we can compare against, but it's a demo
                _argument = args.Arguments[0].ToString();
                _method = args.Method.Name;

                //expires in one minute
                _expires = DateTime.Now.AddMinutes(1);
            }
Example #49
0
 public string GetName(string baseName, MethodInterceptionArgs args)
 {
     var param = args.Method.GetParameters();
     var dic = new Dictionary<string, object>();
     foreach (var p in param)
     {
         dic.Add(p.Name, args.Arguments[p.Position]);
     }
     return GetName(baseName, args.Method as MethodInfo, dic);
 }
Example #50
0
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			var coercer = args.Instance as ICoercer;
			if ( coercer != null )
			{
				var arguments = args.Arguments;
				arguments.SetArgument( 0, coercer.Coerce( arguments.GetArgument( 0 ) ) );
			}
			args.Proceed();
		}
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var instanciaAppService = args.Instance as AppService;

            if (instanciaAppService == null)
                throw new Exception("Se agregó el atributo commits sobre una clase que no hereda de AppService");

            instanciaAppService.BeginTransaction();
            args.Proceed();
            instanciaAppService.Commit();
        }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     base.OnInvoke(args);
     if (((MethodInfo)args.Method).ReturnType == typeof(string))
     {
         if (args.ReturnValue == null)
         {
             args.ReturnValue = string.Empty;
         }
     }
 }
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			var invocation = args.Instance as IParameterizedSourceRelay;
			if ( invocation != null )
			{
				args.ReturnValue = invocation.Get( args.Arguments[0] );
			}
			else
			{
				args.Proceed();
			}
		}
Example #54
0
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			var specification = args.Instance as ISpecification;
			if ( specification != null )
			{
				args.ReturnValue = specification.IsSatisfiedBy( args.Arguments[0] );
			}
			else
			{
				args.Proceed();
			}
		}
 public void RunRoutine(Key key, MethodInterceptionArgs args, ICache cache, Mutex mutex, Action routine)
 {
     using (mutex) //avoid mutex being lost through garbage collection (unsure if required) see: odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx
     {
         for (;;)
         {
             routine();
             cache.Add(key, args.ReturnValue);
             Thread.Sleep(key.DurationToStore - TimeBeforeExpiryToRunRoutine);
         }
     }
 }
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			var controller = args.Instance as IAutoValidationController;
			if ( controller != null && !controller.IsActive )
			{
				args.ReturnValue = controller.Execute( args.Arguments[0], new Invocation( args.GetReturnValue ) ) ?? args.ReturnValue;
			}
			else
			{
				args.Proceed();
			}
		}
		public override void OnInvoke( MethodInterceptionArgs args )
		{
			var source = args.Instance as IPolicySource;
			if ( source != null )
			{
				source.Get().Execute( args.Proceed );
			}
			else
			{
				args.Proceed();
			}
		}
Example #58
0
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     var dispatcher = (Form) args.Instance;
     if (!dispatcher.InvokeRequired)
     {
         args.Proceed();
     }
     else
     {
         dispatcher.Invoke(new Action(args.Proceed));
     }
 }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     var cache = MethodResultCache.GetCache(args.Method);
     var result = cache.GetCachedResult(args.Arguments);
     if (result != null)
     {
         args.ReturnValue = result;
         return;
     }
     base.OnInvoke(args);
     cache.CacheCallResult(args.ReturnValue, args.Arguments);
 }
 public override void OnInvoke(MethodInterceptionArgs args)
 {
     var t = new Task<object>(() => args.Invoke(args.Arguments));
     t.Start();
     //because we need to set ReturnValue, block until task completes
     //again, terrible example, but it's a demo :P
     while (!t.IsCompleted)
     {
         Thread.Sleep(10);
     }
     args.ReturnValue = t.Result;
 }