public void Intercept(IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch (SelenoReceivedException)
            {
                throw;
            }
            catch (Exception e)
            {
                _logger.ErrorFormat(e, "Error invoking {0}.{1}", invocation.TargetType.Name, invocation.Method.Name);
                var filename = _filename + "_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".png";

                if (_camera.ScreenshotTaker == null)
                    _logger.WarnFormat("ITakesScreenshot isn't supported by the web driver {0} so taking a screenshot probably won't work", _camera.Browser.GetType().Name);
                else
                    _logger.DebugFormat("Taking screenshot with filename: {0}", filename);

                try
                {
                    _camera.TakeScreenshot(filename);
                }
                catch (Exception ex)
                {
                    _logger.Error("Error saving a screenshot", ex);
                }

                throw new SelenoReceivedException(e);
            }
        }
        public void Intercept(IInvocation invocation)
        {
            var logger = LogManager.GetLogger(invocation.TargetType);
            try
            {
                StringBuilder sb = null;
                if (logger.IsDebugEnabled)
                {
                    sb = new StringBuilder(invocation.TargetType.FullName)
                        .Append(".")
                        .Append(invocation.Method)
                        .Append("(");
                    for (int i = 0; i < invocation.Arguments.Length; i++)
                    {
                        if (i > 0)
                            sb.Append(", ");
                        sb.Append(invocation.Arguments[i]);
                    }
                    sb.Append(")");
                    logger.Debug(sb);
                }

                invocation.Proceed();
                if (logger.IsDebugEnabled)
                {
                    logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue);
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
        }
        public void Intercept(IInvocation invocation)
        {
            try
            {
                UnitOfWork.Current = new UnitOfWork(_sessionFactory);
                UnitOfWork.Current.BeginTransaction();

                try
                {
                    invocation.Proceed();
                    UnitOfWork.Current.Commit();
                }
                catch
                {
                    try
                    {
                        UnitOfWork.Current.Rollback();
                    }
                    catch(Exception e)
                    {
                        Trace.TraceError(e.Message);
                    }

                    throw;
                }
            }
            finally
            {
                UnitOfWork.Current = null;
            }
        }
        /// <summary>
        /// Caches the invocation.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <param name="cacheKeyProvider">The cache key provider.</param>
        /// <param name="cacheItemSerializer">The cache item serializer.</param>
        /// <param name="cacheStorageMode">The cache storage mode.</param>
        private void CacheInvocation(IInvocation invocation, ICacheKeyProvider cacheKeyProvider, ICacheItemSerializer cacheItemSerializer)
        {
            string hash = cacheKeyProvider.GetCacheKeyForMethod(invocation.InvocationTarget,
                invocation.MethodInvocationTarget, invocation.Arguments);

            string hashedObjectDataType = string.Format(HASHED_DATA_TYPE_FORMAT, hash);

            var cacheProvider = CacheProviderFactory.Default.GetCacheProvider();

            Type type = cacheProvider[hashedObjectDataType] as Type;
            object data = null;
            if (type != null && cacheProvider[hash] != null)
                data = cacheItemSerializer.Deserialize(cacheProvider[hash].ToString(), type,
                    invocation.InvocationTarget, invocation.Method, invocation.Arguments);

            if (data == null)
            {
                invocation.Proceed();
                data = invocation.ReturnValue;
                if (data != null)
                {
                    cacheProvider.Add(hashedObjectDataType, invocation.Method.ReturnType);
                    cacheProvider.Add(hash, cacheItemSerializer.Serialize(data, invocation.InvocationTarget,
                        invocation.Method, invocation.Arguments));
                }
            }
            else
                invocation.ReturnValue = data;
        }
        public override void Intercept(IInvocation invocation)
        {
            // WPF will call a method named add_PropertyChanged to subscribe itself to the property changed events of
            // the given entity. The method to call is stored in invocation.Arguments[0]. We get this and add it to the
            // proxy subscriber list.
            if (invocation.Method.Name.Contains("PropertyChanged"))
            {
                PropertyChangedEventHandler propertyChangedEventHandler = (PropertyChangedEventHandler)invocation.Arguments[0];
                if (invocation.Method.Name.StartsWith("add_"))
                {
                    subscribers += propertyChangedEventHandler;
                }
                else
                {
                    subscribers -= propertyChangedEventHandler;
                }
            }

            // Here we call the actual method of the entity
            base.Intercept(invocation);

            // If the method that was called was actually a proeprty setter (set_Line1 for example) we generate the
            // PropertyChanged event for the property but with event generator the proxy. This must do the trick.
            if (invocation.Method.Name.StartsWith("set_"))
            {
                subscribers(invocation.InvocationTarget, new PropertyChangedEventArgs(invocation.Method.Name.Substring(4)));
            }
        }
		public void Intercept(IInvocation invocation)
		{
			var canExecute = !_eventMetadata.MethodFilters.Any() || _eventMetadata.MethodFilters.Any(e => MatchExpression.Match(e, invocation.Method, invocation.Arguments));

			var returnMethodFilters = _eventMetadata.MethodReturnFilters.Where(e => MatchExpression.Match(e.Item1, invocation.Method, invocation.Arguments)).Select(e => e.Item2).ToList();

			if(canExecute)
			{
				foreach(var i in _dataProviders)
				{
					i.BeforeEvent();
				}
			}

			try
			{
				invocation.Proceed();
			}
			catch(Exception ex)
			{
				if(canExecute && _eventMetadata.ExceptionFilters.Any() && _eventMetadata.ExceptionFilters.Any(e => ex.GetType() == e.Type || (e.IncludeSubTypes && e.Type.IsInstanceOfType(ex))))
				{
					ExecuteEvents(ex);
				}

				throw;
			}

			if(canExecute && !_eventMetadata.ExceptionFilters.Any() && (!returnMethodFilters.Any() || returnMethodFilters.Any(e => e(invocation.ReturnValue))))
			{
				ExecuteEvents();
			}
		}
        public void Intercept(IInvocation invocation)
        {
            switch (invocation.Method.Name)
              {
            case "Close":
              _closedSubscribers(invocation.InvocationTarget, EventArgs.Empty);
              _closedSubscribers = delegate { };
              break;
            case "add_Closed":
              {
            var propertyChangedEventHandler = (EventHandler) invocation.Arguments[0];
            _closedSubscribers += propertyChangedEventHandler;
              }
              break;
            case "remove_Closed":
              {
            var propertyChangedEventHandler = (EventHandler) invocation.Arguments[0];
            _closedSubscribers -= propertyChangedEventHandler;
              }
              break;
              }

              if (invocation.TargetType != null)
            invocation.Proceed();
        }
Example #8
0
			protected override void PreProceed(IInvocation invocation)
			{
				Invoked = true;
				mixin = invocation.InvocationTarget;
				proxy = invocation.Proxy;
				base.PreProceed(invocation);
			}
        public void Intercept(IInvocation invocation)
        {
            if (AbpCrossCuttingConcerns.IsApplied(invocation.InvocationTarget, AbpCrossCuttingConcerns.Auditing))
            {
                invocation.Proceed();
                return;
            }

            if (!_auditingHelper.ShouldSaveAudit(invocation.MethodInvocationTarget))
            {
                invocation.Proceed();
                return;
            }

            var auditInfo = _auditingHelper.CreateAuditInfo(invocation.MethodInvocationTarget, invocation.Arguments);

            if (AsyncHelper.IsAsyncMethod(invocation.Method))
            {
                PerformAsyncAuditing(invocation, auditInfo);
            }
            else
            {
                PerformSyncAuditing(invocation, auditInfo);
            }
        }
        internal override object getTarget(IInvocation ignored)
        {
            if (cached != null)
                return cached;

            ITimeouts timeOuts = WebDriverUnpackUtility.UnpackWebdriver(locator.SearchContext).Manage().Timeouts();
            try
            {
                timeOuts.ImplicitlyWait(zeroTimeSpan);
                waitingForElementList.Timeout = waitingTimeSpan.WaitingDuration;
                var result = waitingForElementList.Until(ReturnWaitingFunction(locator, bys))[0];
                if (shouldCache && cached == null)
                    cached = result;
                return result;
            }
            catch (WebDriverTimeoutException e)
            {
                String bysString = "";
                foreach (var by in bys)
                    bysString = bysString + by.ToString() + " ";
                throw new NoSuchElementException("Couldn't locate an element by these strategies: " + bysString);
            }
            finally
            {
                timeOuts.ImplicitlyWait(waitingTimeSpan.WaitingDuration);
            }
        }
Example #11
0
 private string getKey(IInvocation invocation, CacheAttribute attribute)
 {
     if (attribute.IsKey)
     {
         if (attribute.IsResolve)
         {
             throw new NotSupportedException();
         }
         else
         {
             return attribute.Key;
         }
     }
     else//if (attribute.IsArg)
     {
         if (attribute.IsResolve)
         {
             throw new NotSupportedException();
         }
         else
         {
             object[] args = InterceptorHelper.GetInvocationMethodArgs(invocation);
             if (attribute.Arg <= args.Length)
             {
                 return args[attribute.Arg].ToString();
             }
             else
             {
                 throw new IndexOutOfRangeException();
             }
         }
     }
 }
 /// <summary>
 /// Creates a new <see cref="ConstraintsExpectation"/> instance.
 /// </summary>
 /// <param name="invocation">Invocation for this expectation</param>
 /// <param name="constraints">Constraints.</param>
 /// <param name="expectedRange">Number of method calls for this expectations</param>
 public ConstraintsExpectation(IInvocation invocation,AbstractConstraint[] constraints, Range expectedRange)
     : base(invocation, expectedRange)
 {
     Validate.IsNotNull(()=>constraints);
     this.constraints = constraints;
     ConstraintsMatchMethod();
 }
        public void Intercept(IInvocation invocation)
        {

            ICommand cmd = invocation.Arguments[0] as ICommand;
            ExecutedCommand executedCommand;
            if (cmd == null)
            {
               
                invocation.Proceed();
            }
            else
            {
                //this is a method that accepts a command invoker, should be intercepted
                 executedCommand = new ExecutedCommand()
                {
                    Command = cmd,
                    Id = cmd.Id,
                };
                try
                {
                    invocation.Proceed();
                    _commandStore.Store(executedCommand);
                }
                catch (Exception ex)
                {
                    executedCommand.IsSuccess = false;
                    executedCommand.Error = ex.ToString();
                    _commandStore.Store(executedCommand);
                    throw;
                }

            }


        }
Example #14
0
        /// <summary>
        /// Intercepts the specified invocation.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        public void Intercept(IInvocation invocation)
        {
            var interceptors = Configuration.Interceptors;
            var orderedInterceptors = SortOrderFactory.GetSortOrderStrategy(invocation, interceptors).Sort();
            var validInterceptors = (from interceptor in orderedInterceptors
                                    where Interception.DoesTargetMethodHaveAttribute(invocation, interceptor.TargetAttributeType)
                                    select ResolveHowToCreateInterceptor(interceptor).Create(interceptor)).ToList();

            // 2012.05.14 -tyler brinks - Apparently it is no longer necessary with the new version of Castle to do
            // the "false" interceptions unless they exist without a valid interceptor.
            var falseInvocations = orderedInterceptors.Count() - validInterceptors.Count();

            if (falseInvocations > 0 /*&& validInterceptors.Count == 0*/)
            {
                for (var i = 0; i < falseInvocations; i++)
                {
                    // Not all interceptors run for each type, but all interceptors are interrogated.
                    // If there are 5 interceptors, but only 1 attribute, this handles the other 4
                    // necessary invocations.
                    invocation.Proceed();
                }
            }

            foreach (var interceptor in validInterceptors)
            {
                interceptor.BeforeInvocation();
                interceptor.Intercept(invocation);
                interceptor.AfterInvocation();
            }

            if (ResetPseudoInterceptors != null)
            {
                ResetPseudoInterceptors();
            }
        }
Example #15
0
        protected override void OnException(IInvocation invocation)
        {
            ExceptionContext arg;
            arg = invocation.Arguments[0] as ExceptionContext;
            var args = string.Join(",", arg.RouteData.Values.Select(x => x.Key + " = " + x.Value));
            string message = arg.Exception.Message;
            if(arg.Exception.InnerException != null)
            {
                message = message +" "+ arg.Exception.InnerException.Message;
            }

            if (arg.Exception.GetType() ==  typeof(DbEntityValidationException))
            {
                DbEntityValidationException dbEx = arg.Exception as DbEntityValidationException;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        message = message + "," + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            message = message + arg.Exception.StackTrace;
            _logger.Fatal(createRecord("Exception"
                            , arg.Controller.GetType().Name
                            , arg.Result.ToString()
                            , args
                            , message));
        }
        public CastleInvocationCallAdapter(IInvocation invocation)
        {
            this.invocation = invocation;
            this.Method = invocation.Method;

            this.Arguments = new ArgumentCollection(invocation.Arguments, this.Method);
        }
Example #17
0
        public virtual void PreProcess(IInvocation invocation, CoreInterceptContext context)
        {
            if (invocation.Method.Name.StartsWith("get_") || "ToString".Equals(invocation.Method.Name))
                return;

            context.ActionListener.ActionPerforming((UIItem)context.UiItem);
        }
        public void Intercept(IInvocation invocation)
        {
            var targetMethod = invocation.Method;
            var argumentTypes = invocation.Arguments.Select(a => a.GetType()).ToArray();
            var matchingTypeMethods = _targetType.GetMethods().Where(m =>
            {
                var parameterInfos = m.GetParameters();

                return m.Name == targetMethod.Name &&
                                 argumentTypes.Length == parameterInfos.Length &&
                                 parameterInfos.Select((p, i) => new { p.ParameterType, Index = i })
                                               .All(p => p.ParameterType.IsAssignableFrom(argumentTypes[p.Index]));
            }).ToList();

            if (matchingTypeMethods.Count == 0) return;

            object result;
            if (targetMethod.IsGenericMethod)
            {
                result = matchingTypeMethods.Single(m => m.IsGenericMethodDefinition)
                                            .MakeGenericMethod(targetMethod.GetGenericArguments())
                                            .Invoke(_target, invocation.Arguments);
            }
            else
            {
                result = matchingTypeMethods.Single(m => !m.IsGenericMethodDefinition).Invoke(_target, invocation.Arguments);
            }

            invocation.ReturnValue = result;
        }
        protected override void OnActionExecuted(IInvocation invocation)
        {
            ActionExecutedContext arg0_3;
                arg0_3 = invocation.Arguments[0] as ActionExecutedContext;

                if (arg0_3.ActionDescriptor.ActionName == "ChangePassword"
                        && arg0_3.HttpContext.Request.RequestType == "POST")
                {
                    if (typeof(RedirectToRouteResult) == arg0_3.Result.GetType())
                    {
                        _audit1.Info(createRecord("AuditChangePassword"
                                       , arg0_3.ActionDescriptor.ControllerDescriptor.ControllerType.BaseType.Name
                                       , arg0_3.ActionDescriptor.ActionName
                                       , ""
                                       , "Попытка смены пароля завершилась успешно"));

                    }
                    else if (typeof(ViewResult) == arg0_3.Result.GetType())
                    {
                        _audit1.Info(createRecord("AuditChangePassword"
                                       , arg0_3.ActionDescriptor.ControllerDescriptor.ControllerType.BaseType.Name
                                       , arg0_3.ActionDescriptor.ActionName
                                       , ""
                                       , "Попытка смены пароля завершилась не успешно"));
                    }
                }
        }
        public void Intercept(IInvocation invocation)
        {
            // let the original call go 1st
            invocation.Proceed();

            // make sure target is setting a property
            if (!invocation.Method.Name.StartsWith("set_")) return;

            var propertyName = invocation.Method.Name.Substring(4);
            var pi = invocation.TargetType.GetProperty(propertyName);

            // check for the [ObservableProperty] attribute
            if (!pi.HasAttribute<ObservablePropertyAttribute>()) return;

            // get reflected info of interception target
            var info = invocation.TargetType.GetFields(
                BindingFlags.Instance | BindingFlags.NonPublic)
                .FirstOrDefault(f => f.FieldType == typeof(PropertyChangedEventHandler));

            if (info != null)
            {
                //get the INPC field, and invoke it if we managed to get it ok
                var evHandler =
                    info.GetValue(invocation.InvocationTarget) as PropertyChangedEventHandler;
                if (evHandler != null)
                    evHandler.Invoke(invocation.InvocationTarget,
                                     new PropertyChangedEventArgs(propertyName));
            }
        }
Example #21
0
 public override void Execute(IInvocation invocation, DbAttributeBase attribute)
 {
     Database db = DatabaseHelper.GetDatabase();
     db.Connection.Open();
     int result = db.Delete(invocation.Arguments.FirstOrDefault());
     base.SetInvocationResult(invocation, result);
 }
        private static void PerformUow(IInvocation invocation, bool isTransactional)
        {
            using (var unitOfWork = IocHelper.ResolveAsDisposable<IUnitOfWork>())
            {
                try
                {
                    UnitOfWorkScope.Current = unitOfWork.Object;
                    UnitOfWorkScope.Current.Initialize(isTransactional);
                    UnitOfWorkScope.Current.Begin();

                    try
                    {
                        invocation.Proceed();
                        UnitOfWorkScope.Current.End();
                    }
                    catch
                    {
                        try { UnitOfWorkScope.Current.Cancel(); } catch { } //Hide exceptions on cancelling
                        throw;
                    }
                }
                finally
                {
                    UnitOfWorkScope.Current = null;
                }
            }
        }
		public void Intercept(IInvocation invocation)
		{
			if (invocation.Method.ReturnType.IsValueType)
			{
				invocation.ReturnValue = Activator.CreateInstance(invocation.Method.ReturnType);
			}
		}
Example #24
0
        protected override void OnError(IInvocation invocation, Exception exception)
        {
            string sw = string.Format("********** {0} **********\n Message: {1}", DateTime.Now, exception.Message);
            if (exception.InnerException != null)
            {
                sw += string.Format(
                    "Inner Exception Type: {0} \n Inner Exception: {1} \n Inner Source: {2}",
                    exception.InnerException.GetType(),
                    exception.InnerException.Message,
                    exception.InnerException.Source);
                if (exception.InnerException.StackTrace != null)
                {
                    sw += string.Format("\n Inner Stack Trace: {0}", exception.InnerException.StackTrace);
                }
            }
            sw += string.Format(
                "\n Exception Type: {0}\n Exception: {1}\n Source: {2}\n Stack Trace: ",
                exception.GetType(),
                exception.Message,
                MethodNameFor(invocation));
            if (exception.StackTrace != null)
            {
                sw += (exception.StackTrace);
            }

            this._logger.Error(
                exception, "There was an error invoking {0} Error details is:{1}.\r\n", MethodNameFor(invocation), sw);

            this._hasError = true;
            base.OnError(invocation, exception);
        }
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.Method.Name;

            // if target method is property getter and return value is null - do interception.
            if (!methodName.StartsWith(PropertyGetMethodPefix) || invocation.ReturnValue != null)
            {
                return;
            }

            // logic here for illustration purpose only and should be moved to separate service.
            if (methodName.StartsWith(PropertyGetMethodPefix))
            {
                object value = null;
                string propertyName = methodName.Substring(PropertyGetMethodPefix.Count());

                PropertyInfo propertyInfo = invocation.TargetType.GetProperty(propertyName);
                var defaultValueAttr = (DefaultValueAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(DefaultValueAttribute));
                if (defaultValueAttr != null)
                {
                    var defaultValue = defaultValueAttr.Value;
                    if (defaultValue != null && invocation.Method.ReturnType.IsInstanceOfType(defaultValue))
                    {
                        value = defaultValue;
                    }
                }

                invocation.ReturnValue = value;
            }
        }
Example #26
0
        public void PreProceed(IInvocation invocation)
        {
            Console.WriteLine("before action executed");

            int indent = 0;

            if (indent > 0)
            {
                Console.Write(" ".PadRight(indent * 4, ' '));
            }

            indent++;

            Console.Write("Intercepting: " + invocation.Method.Name + "(");

            if (invocation.Arguments != null && invocation.Arguments.Length > 0)
            {
                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    if (i != 0) Console.Write(", ");
                    Console.Write(invocation.Arguments[i] == null
                        ? "null"
                        : invocation.Arguments[i].GetType() == typeof(string)
                           ? "\"" + invocation.Arguments[i].ToString() + "\""
                           : invocation.Arguments[i].ToString());
                }
            }

            Console.WriteLine(")");
        }
Example #27
0
 protected override void AfterInvoke(IInvocation invocation)
 {
     this._logger.Info(
         "{0} finished {1}.",
         MethodNameFor(invocation),
         (this._hasError ? "with an error state" : "successfully"));
 }
Example #28
0
        public void Intercept(IInvocation invocation)
        {
            foreach (var matchVsReturnValue in _invocationVersusReturnValue)
            {
                if (matchVsReturnValue.Key.Matches(invocation.Method, invocation.Arguments))
                {
                    invocation.ReturnValue = matchVsReturnValue.Value.Produce(invocation.Arguments);
                    return;
                }
            }

            if (Fallback != null)
            {
                invocation.ReturnValue = invocation.Method.Invoke(Fallback, invocation.Arguments);
            }
            else
            {
                if (invocation.Method.ReturnType != typeof(void))
                {
                    if (invocation.Method.ReturnType.IsValueType)
                        invocation.ReturnValue = Activator.CreateInstance(invocation.Method.ReturnType);
                    else
                        invocation.ReturnValue = null;
                }
            }
        }
        public void Intercept(IInvocation invocation)
        {
            var methodName = invocation.Method.Name;
            var arguments = invocation.Arguments;
            var proxy = invocation.Proxy;
            var isEditableObject = proxy is IEditableObject;

            if (invocation.Method.DeclaringType.Equals(typeof (INotifyPropertyChanged)))
            {
                if (methodName == "add_PropertyChanged")
                {
                    StoreHandler((Delegate) arguments[0]);
                }
                if (methodName == "remove_PropertyChanged")
                {
                    RemoveHandler((Delegate) arguments[0]);
                }
            }

            if (!ShouldProceedWithInvocation(methodName))
                return;

            invocation.Proceed();

            NotifyPropertyChanged(methodName, proxy, isEditableObject);
        }
Example #30
0
        public override void Intercept(IInvocation invocation)
        {
            try {
                invocation.Proceed();
            } catch (Exception eOnInvocation) {
                
                if (Preferences.Log) {
//                    try {
                        if (invocation.TargetType.IsSubclassOf(typeof(UiaCommand))) {
                            
                            AutomationFactory.GetLogHelper(string.Empty).Error(eOnInvocation.Message);
//                            var cmdlet =
//                                (invocation.InvocationTarget as UiaCommand).Cmdlet;
//                            var logger =
//                                AutomationFactory.GetLogger();
//                            logger.LogCmdlet(cmdlet);
                        }
//                    }
//                    catch (Exception eLoggingAspect) {
//                        // Console.WriteLine(eLoggingAspect.Message);
//                    }
                }
                
                var eNewException =
                    new Exception("Class " + invocation.TargetType.Name + ", method " + invocation.Method.Name + ": " + eOnInvocation.Message);
                throw eNewException;
            }
            
        }
 protected override void OnSuccess(IInvocation invocation)
 {
     _cacheManager.RemoveByPattern(_pattern);
 }
Example #32
0
 protected virtual void OnSuccess(IInvocation invocation)
 {
 }
Example #33
0
 protected virtual void OnException(IInvocation invocation, System.Exception e)
 {
 }
Example #34
0
 protected virtual void OnAfter(IInvocation invocation)
 {
 }
Example #35
0
 public void Intercept(IInvocation invocation)
 {
     count++;
     invocation.Proceed();
 }
Example #36
0
 public void Intercept(IInvocation invocation)
 {
     Console.WriteLine("Aspect 2");
     invocation.Proceed();
 }
Example #37
0
 public virtual void Intercept(IInvocation invocation)
 {
 }
Example #38
0
 public override void Intercept(IInvocation invocation)
 {
     base.Intercept(invocation);
 }
Example #39
0
 protected override void PreProceed(IInvocation invocation, params object[] args)
 {
     base.PreProceed(invocation, args);
 }
 public DynamicProxyInvocationContext(IInvocation invocation)
 {
     _invocation = invocation;
 }
 public TrackingInvocation(IInvocation backingInvocation)
 {
     _backingInvocation = backingInvocation ?? throw new ArgumentNullException(nameof(backingInvocation));
 }
        public void Intercept(IInvocation invocation)
        {
            if (!IsInitialized)
            {
                return;
            }
            if (invocation.Method.IsSetter() && !_InRejectChanges)
            {
                if (_ChangeTrackingStatus == ChangeStatus.Deleted)
                {
                    throw new InvalidOperationException("Can not modify deleted object");
                }
                string propertyName         = invocation.Method.PropertyName();
                bool   noOriginalValueFound = !_OriginalValueDictionary.ContainsKey(propertyName);

                object originalValue = noOriginalValueFound ? _Properties[propertyName].GetValue(invocation.Proxy, null) : _OriginalValueDictionary[propertyName];
                invocation.Proceed();
                object newValue = _Properties[propertyName].GetValue(invocation.Proxy, null);

                if (!ReferenceEquals(originalValue, newValue))
                {
                    UnsubscribeFromChildStatusChanged(propertyName, originalValue);
                    SubscribeToChildStatusChanged(invocation.Proxy, propertyName, newValue);
                }
                if (noOriginalValueFound && !Equals(originalValue, newValue))
                {
                    _OriginalValueDictionary.Add(propertyName, originalValue);
                    SetAndRaiseStatusChanged(invocation.Proxy, false);
                }
                else if (!noOriginalValueFound && Equals(originalValue, newValue))
                {
                    _OriginalValueDictionary.Remove(propertyName);
                    SetAndRaiseStatusChanged(invocation.Proxy, false);
                }
                return;
            }
            else if (invocation.Method.IsGetter())
            {
                string propertyName = invocation.Method.PropertyName();
                if (propertyName == nameof(IChangeTrackable.ChangeTrackingStatus))
                {
                    invocation.ReturnValue = _ChangeTrackingStatus;
                }
                else if (propertyName == nameof(System.ComponentModel.IChangeTracking.IsChanged))
                {
                    invocation.ReturnValue = _ChangeTrackingStatus != ChangeStatus.Unchanged;
                }
                else if (propertyName == nameof(IChangeTrackable.ChangedProperties))
                {
                    invocation.ReturnValue = GetChangedProperties();
                }
                else
                {
                    invocation.Proceed();
                    SubscribeToChildStatusChanged(invocation.Proxy, propertyName, invocation.ReturnValue);
                }
                return;
            }
            switch (invocation.Method.Name)
            {
            case nameof(IChangeTrackable <object> .GetOriginalValue):
                invocation.ReturnValue = ((dynamic)this).GetOriginalValue((T)invocation.Proxy, (dynamic)invocation.Arguments[0]);
                break;

            case nameof(IChangeTrackable <object> .GetOriginal):
                invocation.ReturnValue = GetOriginal((T)invocation.Proxy);
                break;

            case nameof(IChangeTrackable <object> .GetCurrent):
                invocation.ReturnValue = GetCurrent((T)invocation.Proxy);
                break;

            case "add_StatusChanged":
                _StatusChanged += (EventHandler)invocation.Arguments[0];
                break;

            case "remove_StatusChanged":
                _StatusChanged -= (EventHandler)invocation.Arguments[0];
                break;

            case "Delete":
                invocation.ReturnValue = Delete(invocation.Proxy);
                break;

            case "UnDelete":
                invocation.ReturnValue = UnDelete(invocation.Proxy);
                break;

            case "AcceptChanges":
                AcceptChanges(invocation.Proxy);
                break;

            case "RejectChanges":
                RejectChanges(invocation.Proxy);
                break;

            default:
                invocation.Proceed();
                break;
            }
        }
Example #43
0
 private void ExecuteAsync(IInvocation invocation)
 {
     invocation.ReturnValue = InvokeCallAsync(invocation);
 }
Example #44
0
 private void HandleChanging(IInvocation invocation, IPropertyBase property, IEqualityComparer?comparer)
 {
     if (_checkEquality)
     {
         var oldValue = property.GetGetter().GetClrValue(invocation.Proxy);
         var newValue = invocation.Arguments[^ 1];
 protected override void OnSuccess(IInvocation invocation) //işlemlerin başarılı olması durumunda bellekteki cache uçurulur. Yani silinir yeni cache oluşturulur.
 {                                                         //Ne den başarı durumunda ya ekleme hatalı olursa diye cache silmemmek için
     _cacheManager.RemoveByPattern(_pattern);
 }
 protected virtual void OnBefore(IInvocation invocation)
 {
 }
Example #47
0
        }                                                                                   //genel bilgi :Virtual metodlar senin ezmeni bekleyen metodlardır.

        protected virtual void OnAfter(IInvocation invocation)
        {
        }                                                                                  //Biz bir Aspect yazdığımız zaman onun nerede çalışsın istiyorsak gidip onun ilgili metodlarını eziyoruz.(OnBefore,OnAfter vs..)
 public void Intercept(IInvocation invocation)
 {
     invocation.Proceed();
     invocation.ReturnValue = "(" + invocation.ReturnValue + ")";
 }
 /// <summary>
 /// Override in derived classes to receive signals prior method <paramref name="invocation"/>.
 /// </summary>
 /// <param name="invocation">The method invocation.</param>
 /// <returns>The custom object used to maintain state between <see cref="StartingInvocation"/> and
 /// <see cref="CompletedInvocation(IInvocation, TState, object)"/>.</returns>
 protected virtual TState StartingInvocation(IInvocation invocation)
 {
     return(null);
 }
Example #50
0
 protected virtual void OnBefore(IInvocation invocation)
 {
 }                                                                                   //genel bilgi :Virtual metodlar senin ezmeni bekleyen metodlardır.
Example #51
0
        protected override void OnException(IInvocation invocation, System.Exception e)
        {
            LogDetailWithException logDetailWithException = GetLogDetailWithException(invocation, e);

            _loggerServiceBase.Error(logDetailWithException);
        }
 /// <summary>
 /// Override in derived classes to receive signals after method <paramref name="invocation"/>.
 /// </summary>
 /// <param name="invocation">The method invocation.</param>
 /// <param name="state">The custom object used to maintain state between
 /// <see cref="StartingInvocation(IInvocation)"/> and
 /// <see cref="CompletedInvocation(IInvocation, TState)"/>.</param>
 protected virtual void CompletedInvocation(IInvocation invocation, TState state)
 {
 }
Example #53
0
        public override IClusterResult DoInvoke(IClientPool pool, ILoadBalance loadbalance, URL address, IList <URL> urls, IInvocation invocation)
        {
            var       goodUrls  = new List <URL>();
            var       badUrls   = new List <BadUrl>();
            IResult   result    = null;
            Exception exception = null;

            checkInvokers(urls, invocation);
            var invoker = base.select(loadbalance, invocation, urls, null);

            try
            {
                var client = pool.GetClient(invoker);
                try
                {
                    var refer = client.Refer();
                    result = refer.Invoke(invocation);
                    pool.Recovery(client);
                    goodUrls.Add(invoker);
                }
                catch (Exception ex)
                {
                    pool.Recovery(client);
                    throw ex;
                }
            }
            catch (Exception e)
            {
                logger.Error("Failback to invoke method " + invocation.MethodInfo.Name + ", wait for retry in background. Ignored exception: " + e.Message + ", ", e);
                addFailed(pool, invocation, invoker);
                result    = new RpcResult(); // ignore
                exception = e;
                badUrls.Add(new BadUrl {
                    Url = invoker, BadTime = DateTime.Now, CurrentException = exception
                });
            }

            return(new ClusterResult(result, goodUrls, badUrls, exception, false));
        }
 /// <summary>
 /// Override in derived classes to receive signals after method <paramref name="invocation"/>.
 /// </summary>
 /// <param name="invocation">The method invocation.</param>
 /// <param name="state">The custom object used to maintain state between
 /// <see cref="StartingInvocation(IInvocation)"/> and
 /// <see cref="CompletedInvocation(IInvocation, TState, object)"/>.</param>
 /// <param name="returnValue">
 /// The underlying return value of the <paramref name="invocation"/>; or <see langword="null"/> if the
 /// invocation did not return a value.
 /// </param>
 protected virtual void CompletedInvocation(IInvocation invocation, TState state, object returnValue)
 {
     CompletedInvocation(invocation, state);
 }
Example #55
0
 ///<summary>
 ///</summary>
 public void PerformAgainst(IInvocation invocation)
 {
     proxyInstance.HandleEvent(invocation.Method, invocation.Arguments);
 }
 public void Intercept(IInvocation invocation)
 {
     _cachedGeneration.SetupReturnValueFor(invocation, _instanceSource);
 }
Example #57
0
        protected override void OnBefore(IInvocation invocation)
        {
            var logDetail = GetLogDetail(invocation);

            _loggerServiceBase.Info(logDetail);
        }
Example #58
0
 public void Intercept(IInvocation invocation)
 {
     Assert.IsNotInstanceOf(typeof(IChangeProxyTarget), invocation);
     invocation.Proceed();
 }
Example #59
0
 /// <summary>
 /// intercept as an asynchronous operation.
 /// </summary>
 /// <param name="invocation">The method invocation.</param>
 /// <param name="proceedInfo">The <see cref="T:Castle.DynamicProxy.IInvocationProceedInfo" />.</param>
 /// <param name="proceed">The function to proceed the <paramref name="proceedInfo" />.</param>
 /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> object that represents the asynchronous operation.</returns>
 protected override async Task InterceptAsync(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func <IInvocation, IInvocationProceedInfo, Task> proceed)
 {
     await _interceptor.InterceptAsync(
         new CastleMethodInvocationAdapter(invocation, proceedInfo, proceed)
         );
 }
 public void Intercept(IInvocation invocation)
 {
     // invocation.Method contains the MethodInfo
     // of the actually called method.
     AuthorizeMethod(invocation.Method);
 }