public object Invoke(IMethodInvocation invocation) { string assemblyName = invocation.TargetType.Assembly.GetName().Name; string className = invocation.TargetType.Name; string methodName = invocation.Method.Name; if (assemblyName == "IBB360.Socials" && className == "ActivityApi" && methodName == "BulkInsertProfilerMessages") { return(invocation.Proceed()); } PerfProfiler p = new PerfProfiler(); p.OnMethodEnter(); try { return(invocation.Proceed()); } catch { p.OnMethodException(); throw; } finally { string requestUrl = ""; if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null) { requestUrl = HttpContext.Current.Request.Url.ToString(); } p.OnMethodExit(requestUrl, assemblyName, className, methodName); } }
public object Invoke(IMethodInvocation invocation) { TargetType = invocation.TargetType; MethodInfo methodInfo = invocation.Method; if (!ShouldBeIntercepted(methodInfo)) { return(invocation.Proceed()); } else { BeforeMethodExecution(methodInfo); try { object result = invocation.Proceed(); AfterMethodExecution(methodInfo); return(result); } catch (Exception) { DisposeConversationOnException(); throw; } } }
public object Intercept(IMethodInvocation invocation, params object[] args) { MethodInfo methodInfo = invocation.MethodInvocationTarget; if (!methodInfo.IsDefined(typeof(TransactionAttribute), true)) { return(invocation.Proceed(args)); } else { object[] attrs = methodInfo.GetCustomAttributes(typeof(TransactionAttribute), true); TransactionAttribute transactionAtt = (TransactionAttribute)attrs[0]; ITransactionManager manager = (ITransactionManager)_kernel[typeof(ITransactionManager)]; ITransaction transaction = manager.CreateTransaction( transactionAtt.TransactionMode, transactionAtt.IsolationMode); if (transaction == null) { return(invocation.Proceed(args)); } object value = null; transaction.Begin(); try { value = invocation.Proceed(args); transaction.Commit(); } catch (TransactionException) { // Whoops. Special case, let's throw without // attempt to rollback anything throw; } catch (Exception) { transaction.Rollback(); throw; } finally { manager.Dispose(transaction); } return(value); } }
public object Intercept(IMethodInvocation invocation, params object[] args) { if (invocation.Method.Name.Equals("Sum")) { object result = invocation.Proceed(args); return(((int)result) + 1); } return(invocation.Proceed(args)); }
public object Invoke(IMethodInvocation invocation) { if (invocation.Method.Name != "GetWebRequest") return invocation.Proceed(); var request = (WebRequest) invocation.Proceed(); if (request != null) _modifier.ModifyRequest(request); return request; }
/// <summary> /// Obtains return value either from cache or by invoking target method /// and caches it if necessary. /// </summary> /// <param name="invocation"> /// The method invocation that is being intercepted. /// </param> /// <param name="resultInfo"> /// Attribute specifying where and how to cache return value. Can be <c>null</c>, /// in which case no caching of the result as a whole will be performed /// (if the result is collection, individual items could still be cached separately). /// </param> /// <param name="vars"> /// Variables for expression evaluation. /// </param> /// <param name="cacheHit"> /// Returns <c>true</c> if the return value was found in cache, <c>false</c> otherwise. /// </param> /// <returns> /// Return value for the specified <paramref name="invocation"/>. /// </returns> private object GetReturnValue(IMethodInvocation invocation, CacheResultAttribute resultInfo, IDictionary vars, out bool cacheHit) { if (resultInfo != null) { #region Instrumentation bool isLogDebugEnabled = logger.IsDebugEnabled; #endregion AssertUtils.ArgumentNotNull(resultInfo.KeyExpression, "Key", "The cache attribute is missing the key definition."); object returnValue = null; object resultKey = resultInfo.KeyExpression.GetValue(null, vars); ICache cache = GetCache(resultInfo.CacheName); returnValue = cache.Get(resultKey); cacheHit = (returnValue != null); if (!cacheHit) { #region Instrumentation if (isLogDebugEnabled) { logger.Debug(String.Format("Object for key [{0}] was not found in cache [{1}]. Proceeding...", resultKey, resultInfo.CacheName)); } #endregion returnValue = invocation.Proceed(); if (EvalCondition(resultInfo.Condition, resultInfo.ConditionExpression, returnValue, vars)) { #region Instrumentation if (isLogDebugEnabled) { logger.Debug(String.Format("Caching object for key [{0}] into cache [{1}].", resultKey, resultInfo.CacheName)); } #endregion cache.Insert(resultKey, (returnValue == null) ? NullValue : returnValue, resultInfo.TimeToLiveTimeSpan); } } else { #region Instrumentation if (isLogDebugEnabled) { logger.Debug(String.Format("Object for key [{0}] found in cache [{1}]. Aborting invocation...", resultKey, resultInfo.CacheName)); } #endregion } return((returnValue == NullValue) ? null : returnValue); } cacheHit = false; return(invocation.Proceed()); }
/// <summary> /// 环绕拦截通知 /// </summary> /// <param name="invocation"></param> /// <returns></returns> public object Invoke(IMethodInvocation invocation) { //对OrderRepository进行方法拦截 if (invocation.Method.Name == "Save") { OrderRepository orderDAL = (OrderRepository)invocation.Target; return(categoryDAL.CheckNo(orderDAL.Order.Category) ? invocation.Proceed() : null); } else { return(invocation.Proceed()); } }
public object Invoke(IMethodInvocation invocation) { // Check if we are using it in a Web Service if (HttpContext.Current == null) { throw new InvalidOperationException("This advice should be applied to a Web Service."); } String name = invocation.Method.Name; if (Array.IndexOf <string>(op, name) < 0) { return(invocation.Proceed()); } // Authentication AuthenticationSoapHeader ash = HttpContext.Current.Items["AuthenticationSoapHeader"] as AuthenticationSoapHeader; if (ash == null || string.IsNullOrEmpty(ash.Token)) { //throw new UnauthorizedAccessException("未授权的访问!"); return(-9999); } #region ////检查是否过期 //DataTable dtToken = mainService.GetDataByKey("T_AppToken", "Token", ash.Token); //if (dtToken.Rows.Count != 1) //{ // //throw new UnauthorizedAccessException("未授权的访问!"); // return RT.ILLEGAL_ACCESS; //} //DateTime activityTime = Convert.ToDateTime(dtToken.Rows[0]["RefreshTime"]); //TimeSpan ts = DateTime.Now - activityTime; //if (ts.TotalHours > 12) //{ // //throw new UnauthorizedAccessException("登录超时!"); // return RT.ILLEGAL_ACCESS; //} //else //{ // //刷新时间 // dtToken.Rows[0]["RefreshTime"] = DateTime.Now; // mainService.UpdateDataTable(dtToken); //} #endregion return(invocation.Proceed()); }
public object Invoke(IMethodInvocation invocation) { ILoggerBase logger = invocation.Target as ILoggerBase; if (logger != null) { StringBuilder sb = null; if (logger.LOG.IsDebugEnabled) { logger.LOG.AppendMethodEnterString(ref sb, invocation.Method, invocation.Arguments); logger.LOG.Debug("$$ METHOD_ENTER: " + sb.ToString()); } try { // INVOKE: object returnValue = invocation.Proceed(); if (logger.LOG.IsDebugEnabled && (invocation.Method.ReturnParameter != null) && (invocation.Method.ReturnParameter.ParameterType != typeof(void))) { if (sb != null) { sb.Length = 0; } logger.LOG.AppendMethodReturnValueString(ref sb, invocation.Method, returnValue); logger.LOG.Debug("$$ METHOD_EXIT: " + sb.ToString()); } return(returnValue); } catch (Exception e) { if (logger.LOG.IsErrorEnabled) { if (sb != null) { sb.Length = 0; } logger.LOG.AppendMethodErrorString(ref sb, invocation.Method, e); logger.LOG.Error("$$ METHOD_ERROR: " + sb.ToString()); } throw; } } else { return(invocation.Proceed()); } }
public object Invoke(IMethodInvocation invocation) { Console.Out.WriteLine("Advice executing; calling the advised method..."); object returnValue = invocation.Proceed(); Console.Out.WriteLine("Advice executed; advised method returned " + returnValue); return returnValue; }
public object Invoke(IMethodInvocation invocation) { if (invocation.Method.ReturnType != typeof(string[])) throw new NotSupportedException( "StringArrayFilterAdvice must be applied on methods " + "that return an array of string."); string[] stringArray = (string[])invocation.Proceed(); if (_pattern.Length > 0) { List<string> strings = new List<string>(); foreach (string item in stringArray) { if (PatternMatchUtils.SimpleMatch(_pattern, item)) { strings.Add(item); } } return strings.ToArray(); } return stringArray; }
public object Invoke(IMethodInvocation invocation) { var trs = (EventPublishAttribute)invocation.Method.GetCustomAttributes(typeof(EventPublishAttribute), false)[0]; object returnValue = null; try { if (trs.Pointcut == PubulishPointcut.Before || trs.Pointcut == PubulishPointcut.Both) { if(_log.IsDebugEnabled)_log.Debug("���ص�һ���¼��������� ǰ��:" + invocation.TargetType.FullName + ", " + invocation.Method.Name); EventAggregator.Publish(GetEventModel(trs, invocation)); } returnValue = invocation.Proceed(); if (trs.Pointcut == PubulishPointcut.After || trs.Pointcut == PubulishPointcut.Both) { if (_log.IsDebugEnabled) _log.Debug("���ص�һ���¼��������� ����:" + invocation.TargetType.FullName + ", " + invocation.Method.Name); EventAggregator.Publish(GetEventModel(trs, invocation)); } } catch (Exception) { throw; } return returnValue; }
/// <summary> /// AOP Alliance invoke call that handles all transaction plumbing. /// </summary> /// <param name="invocation"> /// The method that is to execute in the context of a transaction. /// </param> /// <returns>The return value from the method invocation.</returns> public object Invoke(IMethodInvocation invocation) { // Work out the target class: may be <code>null</code>. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Type targetType = ( invocation.This != null ) ? invocation.This.GetType() : null; // If the transaction attribute is null, the method is non-transactional. TransactionInfo txnInfo = CreateTransactionIfNecessary( invocation.Method, targetType ); object returnValue = null; try { // This is an around advice. // Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. returnValue = invocation.Proceed(); } catch ( Exception ex ) { // target invocation exception CompleteTransactionAfterThrowing( txnInfo, ex ); throw; } finally { CleanupTransactionInfo( txnInfo ); } CommitTransactionAfterReturning( txnInfo ); return returnValue; }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("Before: {0}", invocation.Method.Name); var returnValue = (int)invocation.Proceed() * 2; Console.WriteLine("After: {0}", invocation.Method.Name); return returnValue; }
public void SunnyDayLoggingAllOptionalInformationCorrectly() { ILog log = A.Fake <ILog>(); IMethodInvocation methodInvocation = A.Fake <IMethodInvocation>(); MethodInfo mi = typeof(Dog).GetMethod("Bark"); //two additional calls the method are to retrieve the method name on entry/exit... A.CallTo(() => methodInvocation.Method).Returns(mi); int[] luckyNumbers = new int[] { 1, 2, 3 }; object[] args = new object[] { "hello", luckyNumbers }; A.CallTo(() => methodInvocation.Arguments).Returns(args); A.CallTo(() => log.IsTraceEnabled).Returns(true); A.CallTo(() => methodInvocation.Proceed()).Returns(4); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); loggingAdvice.LogExecutionTime = true; loggingAdvice.LogMethodArguments = true; loggingAdvice.LogUniqueIdentifier = true; loggingAdvice.CallInvokeUnderLog(methodInvocation, log); A.CallTo(() => log.Trace(A <string> .That.StartsWith("Entering Bark"))).MustHaveHappened(); A.CallTo(() => log.Trace(A <string> .That.StartsWith("Exiting Bark"))).MustHaveHappened(); }
/// <summary> /// Ejucion del metodo auditable /// </summary> /// <param name="invocation">Datos de invocacion del metodo</param> /// <returns>Resultado de la operacion del metodo autitable</returns> public object Invoke(IMethodInvocation invocation) { object resultadoMetodo = invocation.Proceed(); if (resultadoMetodo is ResultadoOperacionDto) { ResultadoOperacionDto resultadoOperacionDto = (ResultadoOperacionDto)resultadoMetodo; InformacionAuditoriaDto informacionAuditoriaDto = resultadoOperacionDto.InformacionAuditoria; RegistroAuditoria registroAuditoria = new RegistroAuditoria(); if (informacionAuditoriaDto != null) { registroAuditoria.IdEmpresa = informacionAuditoriaDto.Empresa; registroAuditoria.Registro = informacionAuditoriaDto.Registro; registroAuditoria.IdAccionAuditable = informacionAuditoriaDto.Accion; registroAuditoria.IdModulo = informacionAuditoriaDto.Modulo; registroAuditoria.IdUsuario = informacionAuditoriaDto.IdUsuario; registroAuditoria.Fecha = DateTime.Now; if (HttpContext.Current != null) { var session = HttpContext.Current.Session; if (session != null) { if (registroAuditoria.IdEmpresa == 0 && session[ConstantsWeb.IdEmpresaSession] != null) { registroAuditoria.IdEmpresa = long.Parse(session[ConstantsWeb.IdEmpresaSession].ToString()); } } } RegistroAuditoriaRepository.GuardarRegistroAuditoria(registroAuditoria); } } return(resultadoMetodo); }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("DebogLogInterceptor 攔截到一個方法呼叫 = [{0}]", invocation); Debug.Print("DebogLogInterceptor 攔截到一個方法呼叫 = [{0}]", invocation); object result = invocation.Proceed(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //引用stopwatch物件 sw.Reset(); //碼表歸零 sw.Start(); //碼表開始計時 /**************/ /**************/ /***目標程式***/ /**************/ /**************/ sw.Stop();//碼錶停止 //印出所花費的總豪秒數 string result1 = sw.Elapsed.TotalMilliseconds.ToString(); result += result1; Console.WriteLine("回傳的資料已取得 [{0}]", result); Debug.Print("回傳的資料已取得 [{0}]", result); return(result); }
public void SunnyDayLoggingCorrectly() { ILog log = (ILog)mocks.CreateMock(typeof(ILog)); IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); //two additional calls the method are to retrieve the method name on entry/exit... Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any(); Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); log.Trace("Entering ToString"); Expect.Call(methodInvocation.Proceed()).Return(null); log.Trace("Exiting ToString"); mocks.ReplayAll(); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); loggingAdvice.CallInvokeUnderLog(methodInvocation, log); mocks.VerifyAll(); }
public object Invoke(IMethodInvocation invocation) { object result = null; DAO dao = (DAO)invocation.Target; try { result = invocation.Proceed(); dao.OnDone(new DAOEventArgs() { Input = InterceptorUtil.GetParamsMap(invocation.Method, invocation.Arguments), Result = result }); } catch (Exception ex) { dao.OnError(new DAOEventArgs() { Input = InterceptorUtil.GetParamsMap(invocation.Method, invocation.Arguments), Error = ex }); throw ex; } return(result); }
public object Invoke(IMethodInvocation invocation) { ILog log = LogFactory.Create(invocation.TargetType); object result = invocation.Proceed(); log.Write(invocation.TargetType.Name + "." + invocation.Method.Name, LogLevel.Info); return result; }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("开始: " + invocation.TargetType.Name + "." + invocation.Method.Name); object result = invocation.Proceed(); Console.WriteLine("结束: " + invocation.TargetType.Name + "." + invocation.Method.Name); return result; }
/// <summary> /// Subclasses must override this method to perform any tracing around the supplied /// IMethodInvocation. /// </summary> /// <param name="invocation">The method invocation to log</param> /// <param name="log">The log to write messages to</param> /// <returns> /// The result of the call to IMethodInvocation.Proceed() /// </returns> /// <remarks> /// Subclasses are resonsible for ensuring that the IMethodInvocation actually executes /// by calling IMethodInvocation.Proceed(). /// <para> /// By default, the passed-in ILog instance will have log level /// "trace" enabled. Subclasses do not have to check for this again, unless /// they overwrite the IsInterceptorEnabled method to modify /// the default behavior. /// </para> /// </remarks> /// <exception cref="System.Exception"> /// If any of the interceptors in the chain or the target object itself /// throws an exception. /// </exception> protected override object InvokeUnderLog(IMethodInvocation invocation, ILog log) { object returnValue = null; bool exitThroughException = false; DateTime startTime = DateTime.Now; string uniqueIdentifier = null; if (LogUniqueIdentifier) { uniqueIdentifier = CreateUniqueIdentifier(); } try { WriteToLog(LogLevel, log, GetEntryMessage(invocation, uniqueIdentifier), null); returnValue = invocation.Proceed(); return(returnValue); } catch (Exception e) { TimeSpan executionTimeSpan = DateTime.Now - startTime; WriteToLog(LogLevel, log, GetExceptionMessage(invocation, e, executionTimeSpan, uniqueIdentifier), e); exitThroughException = true; throw; } finally { if (!exitThroughException) { TimeSpan executionTimeSpan = DateTime.Now - startTime; WriteToLog(LogLevel, log, GetExitMessage(invocation, returnValue, executionTimeSpan, uniqueIdentifier), null); } } }
public object Invoke(IMethodInvocation invocation) { Log("Intercepted call : about to invoke method '{0}'", invocation.Method.Name); object returnValue = invocation.Proceed(); Log("Intercepted call : returned '{0}'", returnValue); return returnValue; }
public object Invoke(IMethodInvocation invocation) { Calls++; Object ret = invocation.Proceed(); return(ret); }
public void CorrectHandlerUsedForSubclass() { MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); // Extends RemotingException RemotingTimeoutException ex = new RemotingTimeoutException(); MockRepository repository = new MockRepository(); IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); Expect.Call(mi.Proceed()).Throw(ex); repository.ReplayAll(); try { ti.Invoke(mi); Assert.Fail(); } catch (Exception caught) { Assert.AreEqual(ex, caught); } Assert.AreEqual(1, th.GetCalls()); Assert.AreEqual(1, th.GetCalls("RemotingException")); repository.VerifyAll(); }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("111222"); //拦截Save方法 if (invocation.Method.Name == "Save") { ICompanyManager target = (ICompanyManager)invocation.Target; return(manager.IsPass(target.UserName) ? invocation.Proceed() : null); } else { return(invocation.Proceed()); } }
public void ExceptionPathStillLogsCorrectly() { ILog log = A.Fake <ILog>(); IMethodInvocation methodInvocation = A.Fake <IMethodInvocation>(); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); //two additional calls the method are to retrieve the method name on entry/exit... A.CallTo(() => methodInvocation.Method).Returns(mi); A.CallTo(() => log.IsTraceEnabled).Returns(true); Exception e = new ArgumentException("bad value"); A.CallTo(() => methodInvocation.Proceed()).Throws(e); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); try { loggingAdvice.CallInvokeUnderLog(methodInvocation, log); Assert.Fail("Must have propagated the IllegalArgumentException."); } catch (ArgumentException) { } A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened(); A.CallTo(() => log.Trace("Exception thrown in ToString, ToString", e)).MustHaveHappened(); }
} // set in spring cofig public object Invoke(IMethodInvocation invocation) { invocation.Arguments[0] = NewValue; // change the argument object rval = invocation.Proceed(); return(rval); }
/// <summary> /// Handle 'around' advice for services /// </summary> public object Invoke(IMethodInvocation invocation) { object returnValue = null; using (Repository repository = new Repository(Repository.SessionFactory)) { repository.BeginTransaction(); DomainRegistry.Repository = repository; DomainRegistry.Library = null; try { returnValue = invocation.Proceed(); repository.CommitTransaction(); } catch (Exception e) { returnValue = ServiceResult.Error(invocation.Method.ReturnType, e); } } return returnValue; }
public object Invoke(IMethodInvocation invocation) { ConsoleLoggingAttribute[] consoleLoggingInfo = (ConsoleLoggingAttribute[])invocation.Method.GetCustomAttributes(typeof(ConsoleLoggingAttribute), false); if (consoleLoggingInfo.Length > 0) { Color = consoleLoggingInfo[0].Color; } ConsoleColor currentColor = Console.ForegroundColor; Console.ForegroundColor = Color; Console.Out.WriteLine(String.Format( "Intercepted call : about to invoke method '{0}'", invocation.Method.Name)); Console.ForegroundColor = currentColor; object returnValue = invocation.Proceed(); Console.ForegroundColor = Color; Console.Out.WriteLine(String.Format( "Intercepted call : returned '{0}'", returnValue)); Console.ForegroundColor = currentColor; return(returnValue); }
public object Invoke(IMethodInvocation invocation) { ConsoleLoggingAttribute[] consoleLoggingInfo = (ConsoleLoggingAttribute[])invocation.Method.GetCustomAttributes(typeof(ConsoleLoggingAttribute), false); if (consoleLoggingInfo.Length > 0) { Color = consoleLoggingInfo[0].Color; } ConsoleColor currentColor = Console.ForegroundColor; Console.ForegroundColor = Color; Console.Out.WriteLine(String.Format( "Intercepted call : about to invoke method '{0}'", invocation.Method.Name)); Console.ForegroundColor = currentColor; object returnValue = invocation.Proceed(); Console.ForegroundColor = Color; Console.Out.WriteLine(String.Format( "Intercepted call : returned '{0}'", returnValue)); Console.ForegroundColor = currentColor; return returnValue; }
public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping() { MockRepository repository = new MockRepository(); IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice)repository.CreateMock(typeof(IAfterReturningAdvice)); mockAdvice.AfterReturning(null, null, null, null); LastCall.IgnoreArguments(); LastCall.Throw(new FormatException()); Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); Expect.Call(mockInvocation.Arguments).Return(null); Expect.Call(mockInvocation.This).Return(new object()); Expect.Call(mockInvocation.Proceed()).Return(null); repository.ReplayAll(); try { AfterReturningAdviceInterceptor interceptor = new AfterReturningAdviceInterceptor(mockAdvice); interceptor.Invoke(mockInvocation); Assert.Fail("Must have thrown a FormatException by this point."); } catch (FormatException) { } repository.VerifyAll(); }
public void CorrectHandlerUsed() { MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); HttpException ex = new HttpException(); IMethodInvocation mi = A.Fake <IMethodInvocation>(); A.CallTo(() => mi.Method).Returns(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] {})); A.CallTo(() => mi.Arguments).Returns(null); A.CallTo(() => mi.This).Returns(new object()); A.CallTo(() => mi.Proceed()).Throws(ex); try { ti.Invoke(mi); Assert.Fail(); } catch (Exception caught) { Assert.AreEqual(ex, caught); } Assert.AreEqual(1, th.GetCalls()); Assert.AreEqual(1, th.GetCalls("HttpException")); }
public object Intercept(IMethodInvocation invocation, params object[] args) { String name = invocation.Method.Name; if (name.Equals(_entry.CreationMethod)) { if (args.Length == 0 || args[0] == null) { return(_kernel[invocation.Method.ReturnType]); } else { return(_kernel[(String)args[0]]); } } else if (name.Equals(_entry.DestructionMethod)) { if (args.Length == 1) { _kernel.ReleaseComponent(args[0]); return(null); } } return(invocation.Proceed(args)); }
/// <summary> /// Proceeds to the next interceptor in the chain. /// </summary> /// <returns> /// The return value of the method invocation. /// </returns> /// <exception cref="System.Exception"> /// If any of the interceptors at the joinpoint throws an exception. /// </exception> /// <see cref="AopAlliance.Intercept.IJoinpoint.Proceed"/> public virtual object Proceed() { if (this.interceptors == null || this.currentInterceptorIndex == this.interceptors.Count) { AssertJoinpoint(); return(InvokeJoinpoint()); } object interceptor = this.interceptors[this.currentInterceptorIndex]; InterceptorAndDynamicMethodMatcher dynamicMatcher = interceptor as InterceptorAndDynamicMethodMatcher; IMethodInvocation nextInvocation = PrepareMethodInvocationForProceed(this); if (dynamicMatcher != null) { // evaluate dynamic method matcher here: static part will already have // been evaluated and found to match... if (dynamicMatcher.MethodMatcher.Matches( nextInvocation.Method, nextInvocation.TargetType, nextInvocation.Arguments)) { return(dynamicMatcher.Interceptor.Invoke(nextInvocation)); } else { // dynamic match failed; skip this interceptor and invoke the next in the chain... return(nextInvocation.Proceed()); } } else { // it's an interceptor so we just invoke it: the pointcut will have // been evaluated statically before this object was constructed... return(((IMethodInterceptor)interceptor).Invoke(nextInvocation)); } }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("Before {0} on {1}", invocation.Method.Name, invocation.Method.DeclaringType); object returnVal = invocation.Proceed(); Console.WriteLine("After {0} on {1}", invocation.Method.Name, invocation.Method.DeclaringType); return returnVal; }
public object Invoke(IMethodInvocation invocation) { LOG.Debug("Advice executing; calling the advised method [" + invocation.Method.Name + "]"); object returnValue = invocation.Proceed(); LOG.Debug("Advice executed; advised method [" + invocation.Method.Name + "] returned " + returnValue); return returnValue; }
/// <summary> /// AOP Alliance invoke call that handles all transaction plumbing. /// </summary> /// <param name="invocation"> /// The method that is to execute in the context of a transaction. /// </param> /// <returns>The return value from the method invocation.</returns> public object Invoke(IMethodInvocation invocation) { // Work out the target class: may be <code>null</code>. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Type targetType = (invocation.This != null) ? invocation.This.GetType() : null; // If the transaction attribute is null, the method is non-transactional. TransactionInfo txnInfo = CreateTransactionIfNecessary(invocation.Method, targetType); object returnValue = null; try { // This is an around advice. // Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. returnValue = invocation.Proceed(); } catch (Exception ex) { // target invocation exception CompleteTransactionAfterThrowing(txnInfo, ex); throw; } finally { CleanupTransactionInfo(txnInfo); } CommitTransactionAfterReturning(txnInfo); return(returnValue); }
public void HandlerMethodThrowsException() { Exception exception = new Exception(); MyThrowsHandler handler = new ThrowingMyHandler(exception); ThrowsAdviceInterceptor interceptor = new ThrowsAdviceInterceptor(handler); // extends RemotingException... RemotingTimeoutException ex = new RemotingTimeoutException(); MockRepository repository = new MockRepository(); IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); Expect.Call(mi.Proceed()).Throw(ex); repository.ReplayAll(); try { interceptor.Invoke(mi); Assert.Fail("Should not have reached this point, should have thrown an exception."); } catch (Exception caught) { Assert.AreEqual(exception, caught); } Assert.AreEqual(1, handler.GetCalls()); Assert.AreEqual(1, handler.GetCalls("RemotingException")); repository.VerifyAll(); }
public void NoHandlerMethodForThrowable() { MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); Assert.AreEqual(2, ti.HandlerMethodCount); Exception ex = new Exception(); MockRepository repository = new MockRepository(); IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); Expect.Call(mi.Proceed()).Throw(ex); repository.ReplayAll(); try { ti.Invoke(mi); Assert.Fail(); } catch (Exception caught) { Assert.AreEqual(ex, caught); } Assert.AreEqual(0, th.GetCalls()); repository.VerifyAll(); }
public void NestedInnerExceptionsAreNotPickedUp() { MyThrowsHandler throwsHandler = new MyThrowsHandler(); ThrowsAdviceInterceptor throwsInterceptor = new ThrowsAdviceInterceptor(throwsHandler); // nest the exceptions; make sure the advice gets applied because of the inner exception... Exception exception = new FormatException("Parent", new HttpException("Inner")); IMethodInvocation invocation = A.Fake <IMethodInvocation>(); A.CallTo(() => invocation.Proceed()).Throws(exception); try { throwsInterceptor.Invoke(invocation); Assert.Fail("Must have failed (by throwing an exception by this point - check the mock)."); } catch (Exception caught) { Assert.AreEqual(exception, caught); } Assert.AreEqual(0, throwsHandler.GetCalls(), "Must NOT have been handled, 'cos the HttpException was wrapped by " + "another Exception that did not have a handler."); Assert.AreEqual(0, throwsHandler.GetCalls("HttpException"), "Similarly, must NOT have been handled, 'cos the HttpException was wrapped by " + "another Exception that did not have a handler."); }
public void CorrectHandlerUsed() { MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); HttpException ex = new HttpException(); MockRepository repository = new MockRepository(); IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); Expect.Call(mi.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] {})); Expect.Call(mi.Arguments).Return(null); Expect.Call(mi.This).Return(new object()); Expect.Call(mi.Proceed()).Throw(ex); repository.ReplayAll(); try { ti.Invoke(mi); Assert.Fail(); } catch (Exception caught) { Assert.AreEqual(ex, caught); } Assert.AreEqual(1, th.GetCalls()); Assert.AreEqual(1, th.GetCalls("HttpException")); repository.VerifyAll(); }
public object Invoke(IMethodInvocation invocation) { Console.Out.WriteLine("Intercepted call : about to invoke next item in chain..."); object returnValue = invocation.Proceed(); Console.Out.WriteLine("Intercepted call : returned " + returnValue); return returnValue; }
public object Invoke(IMethodInvocation invocation) { // Check if we are using it in a Web Service if (HttpContext.Current == null) { throw new InvalidOperationException("This advice should be applied to a Web Service."); } //方法名 String name = invocation.Method.Name; //参数 object[] args = invocation.Arguments; //记录日志 //LogHelper.Info(string.Format("MethodName->{0}\r\n Argument->{1}", name, JsonConvert.SerializeObject(args))); #region 验证Token // Authentication //AuthenticationSoapHeader ash = HttpContext.Current.Items["AuthenticationSoapHeader"] as AuthenticationSoapHeader; //if (ash == null || string.IsNullOrEmpty(ash.Token)) //{ // throw new UnauthorizedAccessException("未授权的访问!"); //} #endregion return(invocation.Proceed()); }
public object Invoke(IMethodInvocation invocation) { Console.WriteLine("Calling {0}({1}) method...", invocation.Method.Name, string.Join(", ", invocation.Arguments.Select(a => a.ToString()).ToArray())); return invocation.Proceed(); }
public object Invoke(IMethodInvocation invocation) { // Perform logging here, e.g.: var args = string.Join(", ", invocation.Arguments.Select(x => (x ?? string.Empty).ToString())); Debug.WriteLine(string.Format("Spring.NET: {0}({1})", invocation.Method.Name, args)); return invocation.Proceed(); }
public object Invoke(IMethodInvocation invocation) { //开始 ... object result = invocation.Proceed(); //结束 ... return result; }
public object Invoke(IMethodInvocation invocation) { String user = HttpContext.Current.User.Identity.Name; log.Debug(String.Format("{0} - {1} - called by: {2}", invocation.Method.Name, invocation.TargetType.Name,user)); object returnValue = invocation.Proceed(); log.Debug(String.Format("{0} - {1} - finished", invocation.Method.Name, invocation.TargetType.Name)); return returnValue; }
public object Invoke(IMethodInvocation invocation) { ISecurityResource resource = invocation.This as ISecurityResource; Console.Out.WriteLine( "Access granted for " + resource.ResourceType ); return invocation.Proceed(); }
public object Intercept(IMethodInvocation invocation) { MessageCenter.Message.Append(_beforeMessage); var result = invocation.Proceed(); MessageCenter.Message.Append(_afterMessage); return result; }
// private static readonly ILog LOG = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public object Invoke(IMethodInvocation invocation) { System.Console.WriteLine("I'm in the AOP Invoke"); LOG.Debug(String.Format("BaseServiceLogger intercepted call : about to invoke method '{0}'", invocation.Method.Name)); object retVal = invocation.Proceed(); string retString = new TORenderer(retVal).ToString(); LOG.Debug(String.Format("BaseServiceLogger intercepted call : returned '{0}'", retString)); return retVal; }
public object Intercept(IMethodInvocation invocation, params object[] args) { if (_transactionManager.CurrentTransaction != null) { // No support for nested transactions // is necessary return invocation.Proceed(args); } TransactionConfig config = _transactionConfHolder.GetConfig( invocation.Method.DeclaringType ); if (config != null && config.IsMethodTransactional( invocation.Method )) { ITransaction transaction = _transactionManager.CreateTransaction(); object value = null; try { value = invocation.Proceed(args); transaction.Commit(); } catch(Exception ex) { transaction.Rollback(); throw ex; } finally { _transactionManager.Release(transaction); } return value; } else { return invocation.Proceed(args); } }
public object Invoke(IMethodInvocation invocation) { _logger.Enter( invocation.Method.Name ); object value = invocation.Proceed(); _logger.Leave( invocation.Method.Name ); return value; }
/// <summary> /// Displays verbose information about intercepted invocations to the /// system console. /// </summary> /// <param name="invocation"> /// The method invocation that is being intercepted. /// </param> /// <returns> /// The result of the call to the /// <see cref="AopAlliance.Intercept.IJoinpoint.Proceed"/> method of /// the supplied <paramref name="invocation"/>; this return value may /// well have been intercepted by the interceptor. /// </returns> /// <exception cref="System.Exception"> /// If any of the interceptors in the chain or the target object itself /// throws an exception. /// </exception> /// <seealso cref="System.Console"/> /// <seealso cref="AopAlliance.Intercept.IMethodInterceptor.Invoke(IMethodInvocation)"/> public object Invoke(IMethodInvocation invocation) { ++_count; Console.Out.WriteLine("{0} [count={1}, invocation='{2}']", typeof(DebugAdvice).Name, _count, invocation); object returnValue = invocation.Proceed(); Console.Out.WriteLine("{0} ['{1}' invocation returned '{2}']", typeof(DebugAdvice).Name, invocation.Method.Name, returnValue); return returnValue; }
public object Invoke(IMethodInvocation invocation) { object retVal = invocation.Proceed(); if (retVal == null) { retVal = "Whoops! no value setted for this key!"; } return retVal; }
public object Invoke(IMethodInvocation invocation) { ILoggeable target = invocation.This as ILoggeable; if (target != null && invocation.Method.DeclaringType != typeof(ILoggeable)) { target.Log("Invoking " + invocation.Method.Name); } return invocation.Proceed(); }
public object Invoke(IMethodInvocation invocation) { var result = invocation.Proceed(); if ((result == null) && typeof(IEnumerable<ProductViewModel>).IsAssignableFrom(invocation.Method.ReturnType)) { return Enumerable.Empty<ProductViewModel>(); } return result; }
public override object Invoke(IMethodInvocation inv) { object result = inv.Proceed(); if (result is string) { result = (string)result + this.append; } return result; }
public object Invoke(IMethodInvocation invocation) { LogMethod(invocation.Method); LogArguments(invocation.Arguments); object result = invocation.Proceed(); LogReturn(result); return result; }
public virtual object Invoke(IMethodInvocation invocation) { LogAttribute[] logAttributeInfo = invocation.Method.GetCustomAttributes(typeof(LogAttribute), false) as LogAttribute[]; LogAttribute = logAttributeInfo[0]; DoBeforeLog(invocation.Method, invocation.Arguments); object returnValue = invocation.Proceed(); DoAfterLog(invocation.Method, returnValue); return returnValue; }