public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (CachingService.Cache == null) { return(getNext()(input, getNext)); } var cacheKey = CacheUtils.GetCacheKey(input.MethodBase); var cacheValue = CachingService.Cache[cacheKey]; if (cacheValue != null) { return(input.CreateMethodReturn(cacheValue)); } var currentLock = _locks.GetOrAdd(cacheKey, new object()); lock (currentLock) { cacheValue = CachingService.Cache[cacheKey]; if (cacheValue != null) { return(input.CreateMethodReturn(cacheValue)); } if (!NotBlock) { return(AddResultToCache(getNext, input, cacheKey)); } ThreadPoolEx.QueueUserWorkItemWithCatch(state => AddResultToCache(getNext, input, cacheKey)); var result = input.MethodBase.As <MethodInfo>().ReturnType.Create(); AddToCache(result, cacheKey); return(input.CreateMethodReturn(result)); } }
/// <summary> /// Implement this method to execute your behavior processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if (input.MethodBase.Name == "get_IsChangeNotificationActive") { return(input.CreateMethodReturn(_isChangeNotificationActive)); } if (input.MethodBase.Name == "set_IsChangeNotificationActive") { _isChangeNotificationActive = (bool)input.Arguments[0]; return(getNext()(input, getNext)); //must be handled in last Behavior } if (input.MethodBase.Name == "Error" && input.MethodBase.DeclaringType == typeof(IDataErrorInfo)) { return(input.CreateMethodReturn(string.Empty)); } if (input.MethodBase.Name == "get_Item" && input.MethodBase.DeclaringType == typeof(IDataErrorInfo)) { string column = input.Inputs["columnName"] as string; return(input.CreateMethodReturn(ValidateProperty(column, input))); } return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { try { if (this.constructed) { var args = new object[input.Arguments.Count]; input.Arguments.CopyTo(args, 0); var result = base.Invoke((MethodInfo)input.MethodBase, args, input.Target); if (result == AbstractLazyInitializer.InvokeImplementation) { return(input.CreateMethodReturn(input.MethodBase.Invoke(this.GetImplementation(), args))); } return(input.CreateMethodReturn(result)); } return(input.CreateMethodReturn(null)); } catch (TargetInvocationException tie) { ExceptionInternalPreserveStackTrace.Invoke(tie.InnerException, new object[0]); throw tie.InnerException; } }
/// <summary> /// Implement this method to execute your behavior processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if (input.MethodBase == AddEventMethodInfo) { return(AddEventSubscription(input)); } if (input.MethodBase == RemoveEventMethodInfo) { return(RemoveEventSubscription(input)); } if (input.MethodBase.Name == "get_IsChangeNotificationActive") { return(input.CreateMethodReturn(_isChangeNotificationActive)); } if (input.MethodBase.Name == "set_IsChangeNotificationActive") { _isChangeNotificationActive = (bool)input.Arguments[0]; return(input.CreateMethodReturn(null)); } if (_isChangeNotificationActive && IsSetter(input) && IsChange(input)) { IMethodReturn result = getNext()(input, getNext); string propertyName = input.MethodBase.Name.Substring(4); NotifyPropertyChanged(propertyName, input); NotifyAdditionalProperties(input, propertyName); return(result); } return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if ((input.MethodBase.Name.StartsWith("Get") && input.MethodBase.Name != "GetType") || input.MethodBase.Name.StartsWith("get_")) { string cacheKey = input.Arguments.Count > 0 ? (string)input.Arguments[0] : input.MethodBase.Name; object value; if (typedValues.TryGetValue(cacheKey, out value)) { if ((value != null && ((MethodInfo)input.MethodBase).ReturnType.IsAssignableFrom(value.GetType())) || (value == null && !((MethodInfo)input.MethodBase).ReturnType.IsValueType)) { return(input.CreateMethodReturn(value)); } } IMethodReturn result = getNext()(input, getNext); if (result.Exception == null) { Type elementType; if (result.ReturnValue != null && result.ReturnValue.GetType().IsOf(typeof(ObservableCollection <>), out elementType)) { if (parentCollection.IsReadOnly) { try { result = input.CreateMethodReturn(typeof(ReadOnlyCollection <>).MakeGenericType(elementType).CreateInstance(result.ReturnValue)); } catch (Exception ex) { return(input.CreateExceptionMethodReturn(ex)); } } else { ((INotifyCollectionChanged)result.ReturnValue).CollectionChanged += ((sender, e) => parentCollection.Manager.SaveOnCommit(item)); } } typedValues[cacheKey] = result.ReturnValue; } return(result); } if (input.MethodBase.Name.StartsWith("Set")) { if (parentCollection.IsReadOnly) { return(input.CreateExceptionMethodReturn(new InvalidOperationException("Cannot set value to a read-only model"))); } IMethodReturn result = getNext()(input, getNext); if (result.Exception == null) { string fieldName = (string)input.Arguments[0]; typedValues[fieldName] = input.Arguments[1]; parentCollection.Manager.SaveOnCommit(item); } return(result); } return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if (input.MethodBase.Name == "DoNothing") { return(input.CreateMethodReturn(100)); } if (input.MethodBase.Name == "DoNothing1") { return(input.CreateMethodReturn(200)); } return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if (input.MethodBase.Name == "DoNothing") { return input.CreateMethodReturn(100); } if (input.MethodBase.Name == "DoNothing1") { return input.CreateMethodReturn(200); } return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { var methodName = input.MethodBase.Name; var defaultStubMode = GetMethodStubMode(input); lock (_locks.GetOrAdd(methodName, k => new object())) { var rep = LoadRepository(methodName, defaultStubMode); var isSkipMethod = SkipMethods != null && SkipMethods.Contains(methodName); var isSkipRepository = rep.StubMode == StubModeType.Skip; var isSkipped = isSkipMethod || isSkipRepository; if (isSkipped || !IsStubbed()) { return(getNext().Invoke(input, getNext)); } var call = rep.FindCall(input); if (call != null) { return(input.CreateMethodReturn( call.GetResult().ExtractValue(), call.GetAllOutputs().Select(o => o.ExtractValue()).ToArray())); } var isVoid = ((MethodInfo)input.MethodBase).ReturnType == typeof(void); var result = !isVoid ? getNext().Invoke(input, getNext) : input.CreateMethodReturn(null, input.Inputs);; if (result.Exception == null) { var callInfo = MakeCallStub(input, rep, result); rep.Calls.Add(callInfo); var stubMethodPath = GetMethodStubPath(methodName); rep.Save(stubMethodPath); } else { throw new Exception(string.Format("[{0}]{1}\r\n{2}", result.Exception.GetType(), result.Exception.Message, result.Exception.StackTrace)); } return(result); } }
/// <summary> /// Implement this method to execute your behavior processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param> /// <returns> /// Return value from the target. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { if (input.MethodBase.Name == "get_ChangeLog" && input.MethodBase.DeclaringType == typeof(IUnitOfWork)) { return(input.CreateMethodReturn(ChangeLog.Values)); } if (input.MethodBase.Name == "set_ChangeLog" && input.MethodBase.DeclaringType == typeof(IUnitOfWork)) { IEnumerable <UnitOfWorkItem> items = input.Arguments[0] as IEnumerable <UnitOfWorkItem>; ChangeLog.Clear(); if (items != null) { foreach (UnitOfWorkItem item in items) { ChangeLog.Add(item.PropertyName, item); } } return(input.CreateMethodReturn(null)); } IBaseEntity entity = (IBaseEntity)input.Target; //Eine Statusänderung interessiert nur wenn das Objekt ungeändert oder verändert ist if (entity.State == Common.Constants.Constants.EntityState.Unchanged || entity.State == Common.Constants.Constants.EntityState.Modified) { if (IsRelevantProperty(input)) { var propertyName = input.MethodBase.Name.Substring(4); object[] propertyIndex = input .Arguments.Cast <object>() .Where((a, index) => index < input.Arguments.Count - 1) .ToArray(); object oldValue = input.Target.GetType().GetProperty(propertyName).GetValue(input.Target, propertyIndex); object newValue = input.Arguments[input.Arguments.Count - 1]; if (oldValue != newValue) { input.Target.GetType().GetProperty("State").SetValue(input.Target, Common.Constants.Constants.EntityState.Modified); AddToChangeLog(input, propertyName, entity); } } } return(getNext()(input, getNext)); }
/// <summary> /// Http.Context.Cache Provider /// in web Context /// </summary> /// <param name="input"></param> /// <param name="getNext"></param> /// <returns></returns> private IMethodReturn HandleWebCache(IMethodInvocation input, GetNextHandlerDelegate getNext) { //Before invoking the method on the original target var item = _cacheWeb.Get(Key); if (HttpContext.Current.ApplicationInstance.Application.AllKeys.Contains(Key)) { _isDirty = HttpContext.Current.ApplicationInstance.Application[Key].ToString().Equals(Key); } if (_isDirty) { HttpContext.Current.ApplicationInstance.Application.Remove(Key); OnCacheInvalidated(new CacheInvalidateEventArgs { Key = Key }); } if (item != null && !_isDirty) { return(input.CreateMethodReturn(item)); } IMethodReturn result = getNext()(input, getNext); _cacheWeb[Key] = result.ReturnValue; return(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { string methodName = GetKey(input); if (Defaults.TipoInicio == 4) { if (IsInCache(methodName)) { SaveRefParameter(methodName, input); object[] parametros = GetParametros(input.Arguments); return(input.CreateMethodReturn( FetchFromCache(methodName), parametros)); } //else // MessageBox.Show($"No existen datos en el caché para el servicio {methodName}."); } IMethodReturn result = getNext()(input, getNext); if (!input.MethodBase.ToString().Contains("System.Threading.Task") && Utility.ReflectionHelper.IsSerializable(input.MethodBase)) { AddToCache(methodName, result); SaveRefParameter(methodName, input); } return(result); }
/// <summary> /// /// </summary> /// <param name="input">包含传递的参数</param> /// <param name="getNext"></param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { Console.WriteLine("CachingBehavior"); //StringBuilder sbu = new StringBuilder(); //foreach (object item in input.Inputs) //{ // sbu.Append(item.ToString()); //} //sbu.ToString(); IMethodReturn imReturn = null; string key = $"{input.MethodBase.Name}_{Newtonsoft.Json.JsonConvert.SerializeObject(input.Inputs)}"; if (CachingBehaviorDictionary.ContainsKey(key)) //直接返回结果,不再向下执行 { //根据结果创建一个IMethodReturn imReturn = input.CreateMethodReturn(CachingBehaviorDictionary[key]); } else { imReturn = getNext().Invoke(input, getNext); if (imReturn.ReturnValue != null) { CachingBehaviorDictionary.Add(key, imReturn.ReturnValue); } } return(imReturn); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { Console.WriteLine("CachingBehavior"); //把方法的名称和所有的参数列表全部标识为key , 然后放到字典里面; string key = $"{input.MethodBase.Name}_{Newtonsoft.Json.JsonConvert.SerializeObject(input.Inputs)}"; //当方法名和参数都不变, 则表示有缓存 if (CachingBehaviorDictionary.ContainsKey(key)) { return(input.CreateMethodReturn(CachingBehaviorDictionary[key]));//直接返回 [短路器] 不再往下; 包括后面的Behavior也不会再执行了; 因为全部被直接短路了 } else { //如果字典中没有, 则继续执行这里 IMethodReturn result = getNext().Invoke(input, getNext); if (result.ReturnValue != null) //并将其加入到缓存列表中去; 当然缓存中放一个null没有任何意义, 所以这里判断一下 { //不存在则, 加入缓存中 CachingBehaviorDictionary.Add(key, result.ReturnValue); } return(result); } }
/// <summary> /// 方法执行之前调用 /// </summary> /// <remarks> /// 2014年01月10日 10:08 Created By iceStone /// </remarks> /// <param name="input">输入</param> /// <param name="getNext">执行体</param> /// <returns>方法返回结果</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var targetMethod = (MethodInfo)input.MethodBase; if (targetMethod.ReturnType == typeof(void)) { //如果没有返回值,则直接执行方法 return(getNext()(input, getNext)); } var inputs = new object[input.Inputs.Count]; input.Inputs.CopyTo(inputs, 0); string cacheKey = CacheKeyGenerator(targetMethod, inputs); var cachedResult = CacheHelper.Get <object[]>(cacheKey);//HttpRuntime.Cache.Get(cacheKey) as object[]; if (null == cachedResult) { IMethodReturn realReturn = getNext()(input, getNext); if (null == realReturn.Exception) { CacheHelper.Set(cacheKey, new[] { realReturn.ReturnValue }, DateTime.Now.AddSeconds(Duration)); //HttpRuntime.Cache.Insert(cacheKey, new object[] { realReturn.ReturnValue }, null, DateTime.Now.Add(this.ExpirationTime), System.Web.Caching.Cache.NoSlidingExpiration); } return(realReturn); } return(input.CreateMethodReturn(cachedResult[0], new object[] { input.Arguments })); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (this.targetMethodReturnsVoid(input) == true) { return (getNext()(input, getNext)); } Object [] inputs = new Object [ input.Inputs.Count ]; for (Int32 i = 0; i < inputs.Length; ++i) { inputs [ i ] = input.Inputs [ i ]; } String cacheKey = this.createCacheKey(input.MethodBase, inputs); ObjectCache cache = MemoryCache.Default; Object [] cachedResult = (Object []) cache.Get(cacheKey); if (cachedResult == null) { IMethodReturn realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { this.addToCache(cacheKey, realReturn.ReturnValue); } return (realReturn); } IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult [ 0 ], input.Arguments); return (cachedReturn); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (TargetMethodReturnsVoid(input)) { return getNext()(input, getNext); } object[] inputs = new object[input.Inputs.Count]; for (int i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } string cacheKey = KeyGenerator.CreateCacheKey(input.MethodBase, inputs); object[] cachedResult = (object[])HttpRuntime.Cache.Get(cacheKey); if (cachedResult == null) { IMethodReturn realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { AddToCache(cacheKey, realReturn.ReturnValue); } return realReturn; } IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult[0], input.Arguments); return cachedReturn; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { string paramString = GetParameterString(input.Arguments); try { if (Contains(paramString)) { logger.Debug(string.Format("命中{0}缓存,[Group:{1}][Key:{2}][Params:{3}]", this.GetType(), Group, Key, paramString)); return(input.CreateMethodReturn(GetItem(paramString), null)); } IMethodReturn methodReturn = getNext()(input, getNext); if (methodReturn.ReturnValue != null) { SaveItem(paramString, methodReturn.ReturnValue); logger.Debug(string.Format("保存至{0}缓存,[Group:{1}][Key:{2}][Params:{3}]", this.GetType(), Group, Key, paramString)); } return(methodReturn); } catch (Exception ex) { string message = string.Format("{0}异常,[Group:{1}][Key:{2}][Params:{3}]", this.GetType(), Group, Key, paramString); logger.Error(message, new CacheException(message, ex)); return(getNext()(input, getNext)); } }
private IMethodReturn RemoveEventSubscription(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { var subscriber = (PropertyChangedEventHandler)input.Arguments[0]; propertyChanged -= subscriber; return(input.CreateMethodReturn(null)); }
/// <summary> /// Invokes the after call action. This method handles the async methods as well. /// If the method returns <see cref="Task"/> or the generic version the action will be called after the task has been completed. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="afterCall">The action to call after the current method executed.</param> /// <param name="methodReturn">The computed method return.</param> /// <returns>The original method return.</returns> public static IMethodReturn InvokeAfterCall(this IMethodReturn methodReturn, IMethodInvocation input, Action <IMethodReturn> afterCall) { if (afterCall != null) { var returnType = (input.MethodBase as MethodInfo).ReturnType; if (returnType == typeof(Task) || (returnType.IsGenericType && returnType.BaseType == typeof(Task))) { (methodReturn.ReturnValue as Task).ContinueWith((task) => { IMethodReturn asyncResult; if (task.Exception != null) { asyncResult = input.CreateExceptionMethodReturn(task.Exception); } else { object taskReturnValue = null; if (returnType.IsGenericType) { taskReturnValue = (task as dynamic).Result; } asyncResult = input.CreateMethodReturn(taskReturnValue); } afterCall.Invoke(asyncResult); }); } else { afterCall.Invoke(methodReturn); } } return(methodReturn); }
private IMethodReturn RemovePropertyChangingHandler(IMethodInvocation input) { var handler = (PropertyChangingEventHandler)input.Arguments[0]; PropertyChanging -= handler; return(input.CreateMethodReturn(null)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IUnityContainer container = UnityContainer; Type targetType = null; object result = null; var logData = String.Format("ThreadLocalDependencyInjector input: {0}, input.MethodBase: {1} ", input, input.MethodBase); if (input.MethodBase is MethodInfo) { targetType = ((MethodInfo)input.MethodBase).ReturnType; } else { throw new DependencyResolutionException(String.Format("Can't apply TransientDependency injector to {0}. It could be applied only to methods.", input.MethodBase.Name)); } try { result = container.Resolve(targetType); } catch (Exception e) { _logger.Info(String.Format("ThreadLocalDependencyInjector input data: {0}", logData)); throw new DependencyResolutionException(String.Format("Unable to resolve transient dependency of type {0}. See inner exception for details", targetType.FullName), e); } return input.CreateMethodReturn(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { CacheAttribute attr = input.MethodBase.GetCustomAttribute <CacheAttribute>(); if (attr == null) { return(getNext()(input, getNext)); } var arguments = input.MethodBase.GetParameters().ToString(input); string key = $"{arguments}"; string methodName = $"{input.MethodBase.Name}|{input.MethodBase.DeclaringType.FullName}"; var mc = Cache.GetOrAdd(methodName, x => { return(new MemoryCache(x)); }); var data = mc.Get(key); if (data != null) { return(input.CreateMethodReturn(data)); } IMethodReturn result = getNext()(input, getNext); if (result.ReturnValue == null) { return(result); } mc.Add(key, result.ReturnValue, new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(attr.CacheTime)) }); return(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // Before invoking the method on the original target. if (input.MethodBase.Name == "GetConnectionString") { var key = input.Arguments["key"].ToString(); if (IsInCache(key)) { return(input.CreateMethodReturn(FetchFromCache(key))); } else { IMethodReturn routine = getNext()(input, getNext); //Task.Run(() => //{ // AddToCache(key, routine.ReturnValue.ToString()); //}); AddToCache(key, routine.ReturnValue.ToString()); return /*input.CreateMethodReturn(result.ReturnValue.ToString())*/ (routine); } } IMethodReturn result = getNext()(input, getNext); // After invoking the method on the original target. //if (input.MethodBase.Name == "SaveConnectionString") //{ // AddToCache(input.Arguments["key"].ToString(), input.Arguments["val"].ToString()); //} return(result); }
private IMethodReturn InvokeINotifyPropertyChangedMethod(IMethodInvocation input) { if (input.MethodBase.DeclaringType == typeof(INotifyPropertyChanged)) { switch (input.MethodBase.Name) { case "add_PropertyChanged": lock (handlerLock) { handler = (PropertyChangedEventHandler)Delegate.Combine(handler, (Delegate)input.Arguments[0]); } break; case "remove_PropertyChanged": lock (handlerLock) { handler = (PropertyChangedEventHandler)Delegate.Remove(handler, (Delegate)input.Arguments[0]); } break; default: return(input.CreateExceptionMethodReturn(new InvalidOperationException())); } return(input.CreateMethodReturn(null)); } return(null); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (TargetMethodReturnsVoid(input)) { return getNext()(input, getNext); } var inputs = new object[input.Inputs.Count]; for (var i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } var cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs); var cachedResult = MemoryCache.Default.Get(cacheKey); if (cachedResult == null) { var realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { AddToCache(cacheKey, realReturn.ReturnValue); } return realReturn; } var cachedReturn = input.CreateMethodReturn(cachedResult, input.Arguments); return cachedReturn; }
/// <summary> /// Returns previously cached response or invokes method and caches response /// </summary> /// <param name="input"></param> /// <param name="getNext"></param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { //if caching is disabled, leave: if (!CacheConfiguration.Current.Enabled) { return(Proceed(input, getNext)); } //get the cache settings from the attribute & config: var cacheAttribute = GetCacheSettings(input); if (cacheAttribute.Disabled) { return(Proceed(input, getNext)); } //if there's no cache provider, leave: var cache = Cache.Get(cacheAttribute.CacheType); var serializer = Serializer.GetCurrent(cacheAttribute.SerializationFormat); if (cache == null || cache.CacheType == CacheType.Null || serializer == null) { return(Proceed(input, getNext)); } // Log cache request here var returnType = ((MethodInfo)input.MethodBase).ReturnType; var cacheKey = CacheKeyBuilder.GetCacheKey(input, serializer); var cachedValue = cache.Get(returnType, cacheKey, cacheAttribute.SerializationFormat); if (cachedValue == null) { // missed the cache // Log here for instrumentation //call the intended method to set the return value var methodReturn = Proceed(input, getNext); //only cache if we have a real return value & no exception: if (methodReturn != null && methodReturn.ReturnValue != null && methodReturn.Exception == null) { var lifespan = cacheAttribute.Lifespan; if (lifespan.TotalSeconds > 0) { cache.Set(cacheKey, methodReturn.ReturnValue, lifespan, cacheAttribute.SerializationFormat); } else { cache.Set(cacheKey, methodReturn.ReturnValue, cacheAttribute.SerializationFormat); } } return(methodReturn); } else { // hit the cache // Log here for instrumentation } return(input.CreateMethodReturn(cachedValue)); }
private IMethodReturn InvokeINotifyPropertyChangedMethod(IMethodInvocation input) { if (input.MethodBase.DeclaringType == typeof(INotifyPropertyChanged)) { switch (input.MethodBase.Name) { case "add_PropertyChanged": lock (handlerLock) { handler = (PropertyChangedEventHandler)Delegate.Combine(handler, (Delegate)input.Arguments[0]); } break; case "remove_PropertyChanged": lock (handlerLock) { handler = (PropertyChangedEventHandler)Delegate.Remove(handler, (Delegate)input.Arguments[0]); } break; default: return input.CreateExceptionMethodReturn(new InvalidOperationException()); } return input.CreateMethodReturn(null); } return null; }
/// <summary> /// The invoke. /// </summary> /// <param name="input"> /// The input. /// </param> /// <param name="getNext"> /// The get next. /// </param> /// <returns> /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (this.targetMethodReturnsVoid(input)) { return(getNext()(input, getNext)); } var inputs = new object[input.Inputs.Count]; for (int i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } string cacheKey = this.createCacheKey(input.MethodBase, inputs); ObjectCache cache = MemoryCache.Default; var cachedResult = (Object[])cache.Get(cacheKey); if (cachedResult == null) { IMethodReturn realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { this.addToCache(cacheKey, realReturn.ReturnValue); } return(realReturn); } IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult[0], input.Arguments); return(cachedReturn); }
/// <summary> /// Removes the event subscription. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> private IMethodReturn RemoveEventSubscription(IMethodInvocation input) { var subscriber = (PropertyChangedEventHandler)input.Arguments[0]; PropertyChanged -= subscriber; return(input.CreateMethodReturn(null)); }
private IMethodReturn loadUsingCache() { //We need to synchronize calls to the CacheHandler on method level //to prevent duplicate calls to methods that could be cached. lock (input.MethodBase) { if (TargetMethodReturnsVoid(input) || this.cache == null) { return(getNext()(input, getNext)); } var inputs = new object[input.Inputs.Count]; for (var i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } var cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs); var cachedResult = getCachedResult(cacheKey); if (cachedResult == null) { var realReturn = getNext()(input, getNext); if (realReturn.Exception == null && realReturn.ReturnValue != null) { AddToCache(cacheKey, realReturn.ReturnValue); } return(realReturn); } var cachedReturn = input.CreateMethodReturn(cachedResult, input.Arguments); return(cachedReturn); } }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var cacheAttr = GetAttribute(input); if (cacheAttr == null) { return(getNext()(input, getNext)); } string cacheKey = GetCacheKey(cacheAttr, input); ICache cacheHandler = CacheProxy.GetCacheHandler(cacheAttr.CacheMode); switch (cacheAttr.CacheType) { case CacheType.Fetch: if (cacheHandler.Contain(cacheAttr.Group, cacheKey)) { return(input.CreateMethodReturn(cacheHandler.Get(cacheAttr.Group, cacheKey))); } else { var r = getNext()(input, getNext); cacheHandler.Add(cacheAttr.Group, cacheKey, r.ReturnValue); return(r); } case CacheType.Clear: cacheHandler.Remove(cacheAttr.Group, cacheKey); return(getNext()(input, getNext)); } return(getNext()(input, getNext)); }
private IMethodReturn GetMethodReturnFromCache(string cacheKey, IParameterCollection arguments) { var cachedResult = getCachedResult(cacheKey); var returnResult = input.CreateMethodReturn(cachedResult, arguments); return(returnResult); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var cacheAttr = GetAttribute(input); if (cacheAttr == null) return getNext()(input, getNext); string cacheKey = GetCacheKey(cacheAttr, input); ICache cacheHandler = CacheProxy.GetCacheHandler(cacheAttr.CacheMode); switch (cacheAttr.CacheType) { case CacheType.Fetch: if (cacheHandler.Contain(cacheAttr.Group, cacheKey)) { return input.CreateMethodReturn(cacheHandler.Get(cacheAttr.Group, cacheKey)); } else { var r = getNext()(input, getNext); cacheHandler.Add(cacheAttr.Group, cacheKey, r.ReturnValue); return r; } case CacheType.Clear: cacheHandler.Remove(cacheAttr.Group, cacheKey); return getNext()(input, getNext); } return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { MethodInfo targetMethod = (MethodInfo)input.MethodBase; if (targetMethod.ReturnType == typeof(void)) { return(getNext()(input, getNext)); } object[] inputs = new object[input.Inputs.Count]; input.Inputs.CopyTo(inputs, 0); string cacheKey = CacheKeyGenerator(targetMethod, inputs); object[] cachedResult = HttpRuntime.Cache.Get(cacheKey) as object[]; if (null == cachedResult) { IMethodReturn realReturn = getNext()(input, getNext); if (null == realReturn.Exception) { HttpRuntime.Cache.Insert( cacheKey, new object[] { realReturn.ReturnValue }, null, DateTime.Now.Add(this.ExpirationTime), Cache.NoSlidingExpiration); } return(realReturn); } return(input.CreateMethodReturn(cachedResult[0], new object[] { input.Arguments })); }
private IMethodReturn AddPropertyChangedHandler(IMethodInvocation input) { var handler = (PropertyChangedEventHandler)input.Arguments[0]; PropertyChanged += handler; return(input.CreateMethodReturn(null)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { var cacheKey = BuildCacheKey(input); if (_action == CachingAction.Add) { // If cache is empty, execute the target method, retrieve the return value and cache it. if (!_cache.Any(k => k.Key == cacheKey)) { // Execute the target method IMethodReturn returnVal = getNext()(input, getNext); // Cache the return value _cache.Add(cacheKey, returnVal.ReturnValue, GetExpiration()); return(returnVal); } // Otherwise, return the cache result return(input.CreateMethodReturn(_cache.Get(cacheKey), input.Arguments)); } else { _cache.Remove(cacheKey); IMethodReturn returnVal = getNext()(input, getNext); return(returnVal); } }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (TargetMethodReturnsVoid(input)) { return(getNext()(input, getNext)); } var inputs = new object[input.Inputs.Count]; for (var i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } var cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs); var cachedResult = MemoryCache.Default.Get(cacheKey); if (cachedResult == null) { var realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { AddToCache(cacheKey, realReturn.ReturnValue); } return(realReturn); } var cachedReturn = input.CreateMethodReturn(cachedResult, input.Arguments); return(cachedReturn); }
protected IMethodReturn GetProperResponseTypeForMethodToReturn(IMethodInvocation input, string message) { Type retType = (input.MethodBase as MethodInfo).ReturnType; object createdInstance = Activator.CreateInstance(retType); createdInstance.GetType().GetProperty("Error").SetValue(createdInstance, message, null); createdInstance.GetType().GetProperty("IsSuccess").SetValue(createdInstance, false, null); IMethodReturn retu = input.CreateMethodReturn(createdInstance, input.Arguments); return retu; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { string key = (string)input.Inputs[0]; if (key == shortcutKey) { IMethodReturn result = input.CreateMethodReturn(-1); return result; } return getNext()(input, getNext); }
/// <summary> /// Returns previously cached response or invokes method and caches response /// </summary> /// <param name="input"></param> /// <param name="getNext"></param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { //if caching is disabled, leave: if (!CacheConfiguration.Current.Enabled) { return Proceed(input, getNext); } //get the cache settings from the attribute & config: var cacheAttribute = GetCacheSettings(input); if (cacheAttribute.Disabled) { return Proceed(input, getNext); } //if there's no cache provider, leave: var cache = Caching.Cache.Get(cacheAttribute.CacheType); var serializer = Serializer.GetCurrent(cacheAttribute.SerializationFormat); if (cache == null || cache.CacheType == CacheType.Null || serializer == null) { return Proceed(input, getNext); } var targetCategory = InstrumentCacheRequest(input); var returnType = ((MethodInfo)input.MethodBase).ReturnType; var cacheKey = CacheKeyBuilder.GetCacheKey(input, serializer); var cachedValue = cache.Get(returnType, cacheKey, cacheAttribute.SerializationFormat); if (cachedValue == null) { InstrumentCacheMiss(targetCategory, input); //call the intended method to set the return value var methodReturn = Proceed(input, getNext); //only cache if we have a real return value & no exception: if (methodReturn != null && methodReturn.ReturnValue != null && methodReturn.Exception == null) { var lifespan = cacheAttribute.Lifespan; if (lifespan.TotalSeconds > 0) { cache.Set(cacheKey, methodReturn.ReturnValue, lifespan, cacheAttribute.SerializationFormat); } else { cache.Set(cacheKey, methodReturn.ReturnValue, cacheAttribute.SerializationFormat); } } return methodReturn; } else { InstrumentCacheHit(targetCategory, input); } return input.CreateMethodReturn(cachedValue); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (((input.MethodBase as MethodInfo).ReturnType != typeof(void)) || (this.Times == 1)) { return (getNext()(input, getNext)); } else { Parallel.For(0, this.Times, i => getNext()(input, getNext)); return (input.CreateMethodReturn(null)); } }
public IMethodReturn Invoke( IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { var result = getNext()(input, getNext); if (result.Exception is CommunicationException || result.Exception is InvalidOperationException) { this.AlertUser(result.Exception.Message); return input.CreateMethodReturn(null); } return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { UserName = GetUserNameFromInputs(input.Inputs); //Authenticate user if (!UserName.Equals("jbavari")) { throw new AuthenticationException("You aren't an authenticated user. Quit trying to leech our data."); } var toReturn = getNext()(input, getNext); var actualReturn = input.CreateMethodReturn(toReturn.ReturnValue, input.Arguments); return actualReturn; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = null; if ((input.MethodBase as MethodInfo).ReturnType == typeof(void)) { result = input.CreateMethodReturn(null); } else { result = getNext()(input, getNext); } return (result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Boolean isSetter = input.MethodBase.Name.StartsWith("set_") == true; IMethodReturn result = null; if (isSetter != true) { result = getNext()(input, getNext); } else { result = input.CreateMethodReturn(null); } return (result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = null; if ((input.MethodBase as MethodInfo).ReturnType != typeof(void)) { result = getNext()(input, getNext); } else { ThreadPool.QueueUserWorkItem(x => { getNext()(input, getNext); }); result = input.CreateMethodReturn(null); } return (result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { //Before invoking the method on the original target if (input.MethodBase.Name == "GetTenant") { var tenantName = input.Arguments["tenant"].ToString(); if (IsInCache(tenantName)) { return input.CreateMethodReturn(FetchFromCache(tenantName)); } } IMethodReturn result = getNext()(input, getNext); //After invoking the method on the original target if (input.MethodBase.Name == "SaveTenant") { AddToCache(input.Arguments["tenant"]); } return result; }
/// <summary> /// Method called to invoke the method of the wrapped type used to /// inject the logging around the atual method call. /// </summary> /// <param name="input">The method to be invoked.</param> /// <param name="getNext">Gets the next call handler.</param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { //check to see if the cache exits, if so return it var inputs = new object[input.Inputs.Count]; for (int i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } string cacheKey = string.Format("{0}-{1}-{2}", input.MethodBase.DeclaringType.FullName, input.MethodBase.Name, string.Join(",", (from i in inputs select i.ToString()).ToArray())); if (Cache.ContainsKey(cacheKey)) { return input.CreateMethodReturn(Cache[cacheKey], input.Arguments) ; } // Call next handler in chain with the actual method the end of the chain var result = getNext().Invoke(input, getNext); Cache.Add(cacheKey, result.ReturnValue); return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { MethodInfo targetMethod = (MethodInfo)input.MethodBase; if (targetMethod.ReturnType == typeof(void)) { return getNext()(input, getNext); } object[] inputs = new object[input.Inputs.Count]; input.Inputs.CopyTo(inputs, 0); string cacheKey = CacheKeyGenerator(targetMethod, inputs); object[] cachedResult = HttpRuntime.Cache.Get(cacheKey) as object[]; if (null == cachedResult) { IMethodReturn realReturn = getNext()(input, getNext); if (null == realReturn.Exception) { HttpRuntime.Cache.Insert(cacheKey,new object[] { realReturn.ReturnValue }, null, DateTime.Now.Add(this.ExpirationTime),Cache.NoSlidingExpiration); } return realReturn; } return input.CreateMethodReturn(cachedResult[0], new object[] { input.Arguments }); }
private IMethodReturn invoke(IMethodInvocation input, ClientBase<IVCSmyServerService> proxy) { var args = input.Arguments.Cast<object>().ToArray(); var result = input.MethodBase.Invoke(proxy, args); //моделируем закрытие канала, чтобы проверить корректность работы WCFCannel.Create() //при следующем вызове какого-либо метода IService2 через proxy //proxy.Close(); return input.CreateMethodReturn(result, args); }
/// <summary> /// Implement this method to execute your behavior processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { //match specific method if (input.MethodBase.Name != methodName) { return getNext()(input, getNext); } if (this.targetMethodReturnsVoid(input)) { return getNext()(input, getNext); } var inputs = new object[input.Inputs.Count]; for (int i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } string cacheKey = this.createCacheKey(input.MethodBase, inputs); ObjectCache cache = MemoryCache.Default; var cachedResult = (Object[])cache.Get(cacheKey); if (cachedResult == null) { IMethodReturn realReturn = getNext()(input, getNext); if (realReturn.Exception == null) { this.addToCache(cacheKey, realReturn.ReturnValue); } return realReturn; } IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult[0], input.Arguments); return cachedReturn; }
private static IMethodReturn AddEventSubscription(IMethodInvocation input) { var subscriber = (PropertyChangedEventHandler)input.Arguments[0]; (input.Target as INotifyPropertyChanged).PropertyChanged += subscriber; return input.CreateMethodReturn(null); }
/// <summary> /// Implements the caching behavior of this handler. /// </summary> /// <param name="input"> /// <see cref="T:Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation" /> object /// describing the current call. /// </param> /// <param name="getNext">delegate used to get the next handler in the current pipeline.</param> /// <returns>Return value from target method, or cached result if previous inputs have been seen.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (TargetMethodReturnsVoid(input)) { return getNext()(input, getNext); } //object[] array = new object[input.Inputs.Count]; //for (int i = 0; i < array.Length; i++) //{ // array[i] = input.Inputs[i]; //} //string key = this.KeyGenerator.CreateCacheKey(input.MethodBase, array); //object[] array2 = (object[])HttpRuntime.Cache.Get(key); //if (array2 == null) //{ // IMethodReturn methodReturn = getNext()(input, getNext); // if (methodReturn.Exception == null) // { // this.AddToCache(key, methodReturn.ReturnValue); // } // return methodReturn; //} //return input.CreateMethodReturn(array2[0], new object[] //{ // input.Arguments //}); var array = new object[input.Inputs.Count]; for (var i = 0; i < array.Length; i++) { array[i] = input.Inputs[i]; } var key = KeyGenerator.CreateCacheKey(input.MethodBase, array); //object[] array2 = (object[])CacheManager.Provider.Get(key); var array2 = (object[]) HttpRuntime.Cache.Get(key); if (array2 == null) { var methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null) { AddToCache(key, methodReturn.ReturnValue, ExpirationTime); //CacheManager.Provider.Add(key, methodReturn.ReturnValue, ExpirationTime); } return methodReturn; } return input.CreateMethodReturn(array2[0], input.Arguments); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (CachingEnable) { var method = input.MethodBase; var key = method.DeclaringType.FullName + "." + method.Name; ; var valKey = GetValueKey(input); switch (CachingMethod) { case CachingMethod.Get: #region Get try { bool isexists = false; var obj = ExtraCacheManager.Instance.TryGet(key, valKey, ref isexists, this.Hours, this.Minutes, this.Seconds); if (isexists) { var arguments = new object[input.Arguments.Count]; input.Arguments.CopyTo(arguments, 0); return input.CreateMethodReturn(obj); } else { var methodReturn = getNext().Invoke(input, getNext); ExtraCacheManager.Instance.Put(key, valKey, methodReturn.ReturnValue, this.Hours, this.Minutes, this.Seconds, true); return methodReturn; } } catch (Exception ex) { return input.CreateMethodReturn(ex); } #endregion case CachingMethod.Put: #region Put try { var methodReturn = getNext().Invoke(input, getNext); if (Force) { ExtraCacheManager.Instance.Put(key, valKey, methodReturn.ReturnValue, this.Hours, this.Minutes, this.Seconds, true); } else { ExtraCacheManager.Instance.Add(key, valKey, methodReturn.ReturnValue, this.Hours, this.Minutes, this.Seconds); } return methodReturn; } catch (Exception ex) { return input.CreateMethodReturn(ex); } #endregion case CachingMethod.Remove: #region Remove try { if (CorrespondingMethodNames != null && CorrespondingMethodNames.Length > 0) foreach (var removeKey in CorrespondingMethodNames) { ExtraCacheManager.Instance.Clear(removeKey); } var methodReturn = getNext().Invoke(input, getNext); return methodReturn; } catch (Exception ex) { return input.CreateMethodReturn(ex); } #endregion default: break; } } return getNext().Invoke(input, getNext); }
private IMethodReturn CorrectSender(IMethodInvocation input) { return input.CreateMethodReturn(null); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptorDelegate getNext) { string cacheRegion = GetCacheRegion(input.MethodBase); string cacheKey = _cachingAttribute.CacheKey; if (string.IsNullOrEmpty(cacheKey)) { cacheKey = CreateCacheKey(input); } IMethodReturn realReturn; switch (_cachingAttribute.Method) { case CachingAttribute.CachingMethod.Get: if (TargetMethodReturnsVoid(input)) { return getNext()(input, getNext); } var cache = this.GetOrBuildCache(cacheRegion); var cachedResult = (object[])cache.Get(cacheKey); if (cachedResult == null) { realReturn = getNext()(input, getNext); cache.Put(cacheKey, new object[] { realReturn.ReturnValue, realReturn.Outputs }); return realReturn; } else { var outputs =(cachedResult[1] as IParameterCollection).Cast<object>().ToArray(); IMethodReturn cachedReturn = input.CreateMethodReturn(cachedResult[0], outputs); return cachedReturn; } case CachingAttribute.CachingMethod.Put: if (TargetMethodReturnsVoid(input)) { return getNext()(input, getNext); } IMethodReturn methodReturn = getNext().Invoke(input, getNext); this.GetOrBuildCache(cacheRegion).Put(cacheKey, new object[] { methodReturn.ReturnValue, methodReturn.Outputs }); return methodReturn; case CachingAttribute.CachingMethod.Remove: foreach (var region in _cachingAttribute.RelatedAreas) { this.GetOrBuildCache(region).Clear(); } return getNext().Invoke(input, getNext); } return getNext().Invoke(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = input.CreateMethodReturn(null); return result; }
private IMethodReturn ExecuteDoNothing(IMethodInvocation input) { IMethodReturn returnValue = input.CreateMethodReturn(10); return returnValue; }
IMethodReturn MakeReturnMessage(IMethodInvocation input) { IMethodReturn result = input.CreateMethodReturn(MyTargetMethod((int)input.Inputs[0])); return result; }