public void Intercept(IInvocation invocation) { try { var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new MaskedPasswordPropertyResolver() }; if (invocation.Method.Name.ToLower().Equals("execute")) { var executeContext = invocation.GetArgumentValue(0) as ExecuteContext <object>; var arguments = executeContext?.Arguments; this.Log().Info($"===> {invocation.TargetType.FullName}.${invocation.Method.Name} {Environment.NewLine}Routingslip ExecutionId: {executeContext?.ExecutionId}{Environment.NewLine}Message: { JsonConvert.SerializeObject(arguments, Formatting.Indented, settings)} {Environment.NewLine} <==="); } else { var compensateContext = invocation.GetArgumentValue(0) as CompensateContext <object>; var arguments = compensateContext?.Log; this.Log().Info($"===> {invocation.TargetType.FullName}.${invocation.Method.Name}{Environment.NewLine}Routingslip ExecutionId: {compensateContext?.ExecutionId} {Environment.NewLine}Message: { JsonConvert.SerializeObject(arguments, Formatting.Indented, settings)} {Environment.NewLine} <==="); } } catch (Exception ex) { this.Log().Error(ex); this.Log().Info($"===> {invocation.TargetType.FullName}.${invocation.Method.Name}"); } invocation.Proceed(); }
public void Intercept(IInvocation invocation) { var userId = invocation.GetArgumentValue(0); var message = invocation.GetArgumentValue(1); _logger.Log($"User {userId} with Message {message} {DateTime.UtcNow}"); invocation.Proceed(); }
public virtual void Intercept(IInvocation invocation) { if (invocation.Method.DeclaringType == typeof(INotifyPropertyChanged)) { var propertyChangedEventHandler = (PropertyChangedEventHandler)invocation.GetArgumentValue(0); if (invocation.Method.Name.StartsWith("add_")) { subscribers += propertyChangedEventHandler; } else { subscribers -= propertyChangedEventHandler; } return; } invocation.Proceed(); var result = invocation.ReturnValue; // 속성값이 변경되었을 때 PropertyChanged event를 실행시킨다. if (invocation.Method.Name.StartsWith("set_")) { if (IsDebugEnabled) { log.Debug("Raise PropertyChanged event. PropertyName=" + invocation.Method.Name); } subscribers(this, new PropertyChangedEventArgs(invocation.Method.Name.Substring(4))); } invocation.ReturnValue = result; }
public override Task <TResult> Send <TResult>(IInvocation invocation) { #region 如果是get请求,组装url和参数 var index = 0; var sb = new StringBuilder(BaseURL); sb.Append('?'); foreach (var p in invocation.Method.GetParameters()) { var value = invocation.GetArgumentValue(index); sb.Append(p.Name); sb.Append('='); sb.Append(value); sb.Append('&'); index++; } #endregion 如果是get请求,组装url和参数 var url = sb.ToString(); #region 如果是POST请求,组装body #endregion 如果是POST请求,组装body #region 调用远程真正的方法,获取回复 var res = "[{\"ID\":\"111\",\"Name\":\"测试\"}]"; #endregion 调用远程真正的方法,获取回复 var obj = Newtonsoft.Json.JsonConvert.DeserializeObject <TResult>(res); return(Task.FromResult(obj)); }
protected override void PerformProceed(IInvocation invocation) { Guard.Against <InvalidOperationException>( invocation.Method.Name != "Handle" || !invocation.Method.IsPublic || invocation.Arguments.Length != 1, $"Invoked {GetType().Name} interceptor for a non-handle method ({invocation.Method.Name})?!" ); if (IsLockedSaga(invocation.InvocationTarget as Saga) && !IsFlaggedAsDeferred()) { var message = invocation.GetArgumentValue(0); _Log.DebugFormat("Deferring handling of message of type {0}, due to target saga being currently locked.", message?.GetType()); if (MessageContext.HasCurrent) { // The Rebus transport message ID can not be overwritten foreach (var header in MessageContext.GetCurrent().Headers.Where(x => x.Key != Headers.MessageId)) { _bus.AttachHeader(message, header.Key, Convert.ToString(header.Value)); } } _bus.Defer(_settings.LockedSagasDeferInterval, message); MessageContext.GetCurrent().Abort(); // Flag the MessageContext as deferred to avoid generating multiple timeouts // when a message that is handled by multiple sagas has at least one of them locked FlagAsDeferred(); return; } base.PerformProceed(invocation); }
public void Intercept(IInvocation invocation) { PropertyInfo setter = invocation.Method.DeclaringType.GetProperties() .FirstOrDefault(p => p.GetSetMethod() == invocation.Method); if (setter != null && setter.HasAttribute<OutAttribute>()) { string mappingName = setter.GetOutMappingName(); invocation.Proceed(); if (setter.GetGetMethod(true) != null) { data[mappingName] = setter.GetValue(ProxyUtil.GetUnproxiedInstance(invocation.InvocationTarget)); } else { data[mappingName] = invocation.GetArgumentValue(0); } } PropertyInfo getter = invocation.Method.DeclaringType.GetProperties() .FirstOrDefault(p => p.GetGetMethod() == invocation.Method); if (getter != null && getter.HasAttribute<InAttribute>()) { string mappingName = getter.GetInMappingName(); invocation.ReturnValue = data[mappingName]; } }
public void Intercept(IInvocation invocation) { using (var ms = new MemoryStream()) using (var w = new BinaryWriter(ms)) { w.Write(0x01); w.Write(invocation.Method.Name); var parameters = invocation.Method.GetParameters(); for (var i = 0; i < parameters.Length; i++) { w.Write(parameters[i].Name); var val = invocation.GetArgumentValue(i); if (val == null) { w.Write(0x02); continue; } var ptype = parameters[i].ParameterType; if (ptype.IsValueType || ptype == typeof(string) || ptype == typeof(byte[]) || ptype == typeof(char[]) ) { dynamic v = val; w.Write(v); continue; } w.Write(val.ToString()); } w.Write(0x02); _socket.Write(ms.ToArray()); } }
//public DataBindingInterceptor(System.Type persistentClass, object id, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, ISessionImplementor session) // : base(persistentClass, id, getIdentifierMethod, setIdentifierMethod, session) //{ //} public override void Intercept(IInvocation invocation) { object result; if (invocation.Method.DeclaringType == typeof(INotifyPropertyChanged)) { var propertyChangedEventHandler = (PropertyChangedEventHandler)invocation.GetArgumentValue(0); if (invocation.Method.Name.StartsWith("add_")) { subscribers += propertyChangedEventHandler; } else { subscribers -= propertyChangedEventHandler; } return; } base.Intercept(invocation); result = invocation.ReturnValue; if (invocation.Method.Name.StartsWith("set_")) { subscribers(this, new PropertyChangedEventArgs(invocation.Method.Name.Substring(4))); } invocation.ReturnValue = result; }
protected override CompositeKey CalculateKey(IInvocation invocation, string[] keyAttributes = null) { try { CompositeKey result = new CompositeKey(); List<object> argumentsForKey = null; argumentsForKey = new List<object>() { invocation.Method.Name }; result.MinimalKey = invocation.Method.Name; if (keyAttributes != null && keyAttributes.Length > 0) { // note: not expanding parameters of type list/array - the key may be longer than the actual data var values = invocation.Method.GetParameters().Where(p => keyAttributes.Contains(p.Name)).Select( p => invocation.GetArgumentValue(p.Position).ToString()); argumentsForKey.AddRange(values); } result.FullKey = string.Join("-", argumentsForKey); return result; } catch (Exception) { throw; } }
public void Intercept(IInvocation invocation) { PropertyInfo property; ILazyResolverMixin lazyResolverMixin; if (!ShouldInterceptClass(invocation, out lazyResolverMixin)) { invocation.Proceed(); } else if (ShouldInterceptGetMethod(invocation, out property)) { var alias = GetPropertyAlias(invocation); var value = lazyResolverMixin.GetOrResolve(alias, property); invocation.ReturnValue = value; } else if (ShouldInterceptSetMethod(invocation, out property)) { var alias = GetPropertyAlias(invocation); var value = invocation.GetArgumentValue(0); lazyResolverMixin.Set(alias, value); invocation.ReturnValue = value; } else { invocation.Proceed(); } }
/// <summary> /// 获取key /// </summary> /// <param name="invocation"></param> /// <returns></returns> private string GetKey(IInvocation invocation) { var sb = new StringBuilder(); var attrKeys = invocation.MethodInvocationTarget.GetCustomAttributes(typeof(TdbCacheKeyAttribute), true).Select(m => m as TdbCacheKeyAttribute); foreach (var attrKey in attrKeys) { //获取参数值 var param = invocation.GetArgumentValue(attrKey.ParamIndex); //直接获取 if (string.IsNullOrWhiteSpace(attrKey.FromPropertyName)) { sb.Append(this.ToStr(param)); } //从属性获取 else { ///属性不存在 if (CommHelper.IsExistProperty(param, attrKey.FromPropertyName) == false) { throw new TdbException($"[缓存拦截器]找不到属性:{param.GetType().Name}.{attrKey.FromPropertyName}"); } var paramValue = CommHelper.ReflectGet(param, attrKey.FromPropertyName); sb.Append(this.ToStr(paramValue)); } } return(sb.ToString()); }
private async void InterceptAsync(IInvocation invocation) { var methodName = invocation.MethodInvocationTarget.Name.ToUpper(); string key = string.Empty; string loggerInfo = string.Empty; string cacheAction = string.Empty; if (methodName == "ReadPost".ToUpper()) { key = string.Format("PostDto:Id:{0}", invocation.GetArgumentValue(0).ToString()); HandleGetAllOrRead(invocation, key, out cacheAction); } if (methodName == "GetAllPost".ToUpper()) { key = "AllPosts"; HandleGetAllOrRead(invocation, key, out cacheAction); } if (methodName == "UpdatePost".ToUpper() || methodName == "CreatePost".ToUpper()) { cacheAction = "更新集合缓存,"; Handle(invocation, () => { CreateOrUpdateSucceed(invocation); }); } if (methodName == "DeletePost") { cacheAction = "更新集合缓存"; Handle(invocation, () => { DeleteSucceed(invocation); }); } if (methodName == "GetPostsByAuthorId") { var Icache = _cacheManager.GetCache("post"); //获取所有的帖子集合缓存 var allpostsTask = Icache.GetOrDefault("AllPosts"); if (allpostsTask != null) { cacheAction = "从缓存集合获取数据"; var authorId = (Guid)invocation.Arguments[0]; var allposts = ((Task <IList <PostOutput> >)allpostsTask).Result; invocation.ReturnValue = Task.FromResult <IEnumerable <PostOutput> >(allposts.Where(a => a.AuthorId == authorId)); return; } cacheAction = "从数据库获取数据"; invocation.Proceed(); ((Task)invocation.ReturnValue).Wait(); } //After method execution loggerInfo = string.Format("执行了{0}方法, 缓存行为:{1}", methodName, cacheAction); await Task.Run(() => { _logger.InfoFormat(loggerInfo); }); return; }
/// <summary> /// 在拦截的方法开始执行时候调用 /// </summary> /// <param name="invocation"></param> protected override void PerformProceed(IInvocation invocation) { //System.Diagnostics.Trace.WriteLine("执行拦截器PerformProceed方法:"+invocation.Method.Name.ToString()); string methodName = invocation.Method.Name; if (methodName.Equals("Initialize")) //初始化 ApiController 实例 { HttpControllerContext context = (HttpControllerContext)invocation.GetArgumentValue(0); string resultStr = string.Empty; //判断结果 //if (!System.Diagnostics.Debugger.IsAttached) if (!_authAspect.IsAuthenticationByApi(context, out resultStr)) //权限验证是否通过 { if (resultStr == "noLogin") { throw new LoginException("noLogin"); } else if (resultStr == "noAuth") { throw new PermissionLimittedException("noAuth"); } else { throw new PermissionLimittedException("未知错误"); } } else //验证通过之后根据请求的方法需要开启事务 { _transAspect.BeginTransaction(context); } } base.PerformProceed(invocation); }
protected override void PostProceed(IInvocation invocation) { SqlDbContext dbContext = invocation.GetArgumentValue(0) as SqlDbContext; //Log Information about current Execution dbContext.Log(dbContext); base.PostProceed(invocation); }
public void Intercept(IInvocation invocation) { Console.WriteLine("进入拦截方法"); int a = (int)invocation.GetArgumentValue(0); int b = (int)invocation.GetArgumentValue(1); if (a > this._max || b > this._max) { Console.WriteLine(string.Format("参数不能大于{0}", this._max)); throw new ArgumentOutOfRangeException(); } else { invocation.Proceed(); } }
private void InjectDependencyIfNecessary(IInvocation invocation, ILifetimeScope lifetime) { int indexOfDependencyArgument = FindDependencyArgument(invocation.Method); if (indexOfDependencyArgument >= 0 && invocation.GetArgumentValue(indexOfDependencyArgument) == null) { SetDependencyArgument(invocation, indexOfDependencyArgument, lifetime); } }
protected override void HandleIntercept(IInvocation invocation) { var result = (HealthCheckResult)invocation.GetArgumentValue(0); var notification = (Notification)invocation.GetArgumentValue(1); if (Applies(result)) { var prePriority = notification.Priority; Finalise(result, notification); if (notification.Priority != prePriority) { Logger.Debug("Finaliser '{0}' has adjusted the priority from {1} to {2}", GetType().Name, prePriority, notification.Priority); } } invocation.Proceed(); }
protected override void PostProceed(IInvocation invocation) { //System.Diagnostics.Trace.WriteLine("执行拦截器PostProceed方法:"+invocation.Method.Name.ToString()); if (invocation.Method.Name.Equals("ExecuteAsync")) //方法执行完成之后,需要提交事务. { HttpControllerContext context = (HttpControllerContext)invocation.GetArgumentValue(0); _transAspect.CommitTransaction(context, invocation); SessionFactory.SessionUnbind(); } base.PostProceed(invocation); }
public void Intercept(IInvocation invocation) { #if DEBUG Count++; #endif if (invocation.Method.Name.StartsWith("get_", StringComparison.OrdinalIgnoreCase)) { string propertyName = invocation.Method.Name.Substring(4); var property = classMapping.Properties.FirstOrDefault(p => p.Name.Matches(propertyName)); if (property != null) { if (property.HasReference) { invocation.ReturnValue = entityProxyObject.HandleReferencePropertyGet(property); } else if (property.HasOneToMany) { invocation.ReturnValue = entityProxyObject.HandleOneToManyPropertyGet(property); } else { var value = entityProxyObject.GetCurrentFieldValue(property.Column); if (property.CustomTypeConverter != null) invocation.ReturnValue = property.CustomTypeConverter.ConvertTo(value); else invocation.ReturnValue = value; } return; } } else if (invocation.Method.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase)) { string propertyName = invocation.Method.Name.Substring(4); var property = classMapping.Properties.FirstOrDefault(p => p.Name.Matches(propertyName)); if (property != null) { var value = invocation.GetArgumentValue(0); if (property.HasReference) { entityProxyObject.HandleReferencePropertySet(property, value); } else { if (property.CustomTypeConverter != null) entityProxyObject.SetNewFieldValue(property.Column, property.CustomTypeConverter.ConvertFrom(value)); else entityProxyObject.SetNewFieldValue(property.Column, value); } return; } } invocation.Proceed(); }
private static void AddHandler(IInvocation invocation, INotifyInvocation propertyChangedInterceptor) { if (!Handlers.ContainsKey(invocation.InvocationTarget)) { Handlers.Add(invocation.InvocationTarget, new Dictionary <string, PropertyChangedEventHandler>()); } Handlers[invocation.InvocationTarget].Add(invocation.PropertyName(), (o, e) => { propertyChangedInterceptor.Notify(invocation); }); ((INotifyPropertyChanged)invocation.GetArgumentValue(0)).PropertyChanged += Handlers[invocation.InvocationTarget][invocation.PropertyName()]; }
static void AddHandler(IInvocation invocation, PropertyChangedInterceptor propertyChangedInterceptor) { if (!handlers.ContainsKey(invocation.InvocationTarget)) handlers.Add(invocation.InvocationTarget, new Dictionary<string, PropertyChangedEventHandler>()); handlers[invocation.InvocationTarget].Add(invocation.PropertyName(), (o, e) => { propertyChangedInterceptor.Notify(invocation); propertyChangedInterceptor.SetDependents(invocation); }); (invocation.GetArgumentValue(0) as INotifyPropertyChanged).PropertyChanged += handlers[invocation.InvocationTarget][invocation.PropertyName()]; }
/// <summary> /// Intercepts the call in machine processing /// </summary> /// <param name="invocation"> /// Intercepted action invocation /// </param> public void Intercept(IInvocation invocation) { var machineState = invocation.GetArgumentValue(0) as IMachineState; // Bind the grid with the opcodes if its empty if (this.disassemblerForm.IsOpcodeGridViewEmpty()) { this.disassemblerForm.Invoke(new Action(() => this.disassemblerForm.BindOpcodeList(machineState))); } // Refresh the timer status since it's incremented after a cycle this.disassemblerForm.Invoke( new Action(() => this.disassemblerForm.RefreshDisassemblerStatus(machineState))); var currentRowPosition = this.disassemblerForm.GetGridRowPositionFromProgramCounter( machineState.ProgramCounter - 2); var debugAction = DebugOptions.Continue; if (this.disassemblerForm.HasHitBreakPoint(currentRowPosition)) { this.disassemblerForm.SetHitState(currentRowPosition); } var wasPreviouslyDebugging = this.disassemblerForm.IsLineDebugging(currentRowPosition); if (wasPreviouslyDebugging) { debugAction = this.WaitForAction(); } invocation.Proceed(); var nextRowPosition = this.disassemblerForm.GetGridRowPositionFromProgramCounter( machineState.ProgramCounter); if (wasPreviouslyDebugging) { this.disassemblerForm.Invoke( new Action(() => this.disassemblerForm.CleanUpDebuggedLine(currentRowPosition))); if (debugAction == DebugOptions.StepOver) { this.disassemblerForm.Invoke( new Action(() => this.disassemblerForm.SetStepOverState(nextRowPosition))); } } this.disassemblerForm.Invoke( new Action(() => this.disassemblerForm.RefreshDisassemblerStatus(machineState))); }
public void Intercept(IInvocation invocation) { //拦截前 if ((string)invocation.GetArgumentValue(0) == "sss") { Console.WriteLine("拦截前拦截到到了"); } invocation.Proceed(); //拦截后 if ((string)invocation.ReturnValue == "sss") { Console.WriteLine("拦截后拦截到了"); } }
public void Intercept(IInvocation invocation) { #pragma warning disable CC0008 // Use object initializer var packet = new NetworkProtocol.Packet(); packet.Name = invocation.Method.Name; packet.Parameters = invocation.Method.GetParameters() .Select(x => new NetworkProtocol.MethodParameter { Name = x.Name, Value = invocation.GetArgumentValue(x.Position) }) .Where(x => x.Value != null) .ToArray(); _socket.Write(packet); #pragma warning restore CC0008 // Use object initializer }
/// <summary> /// 在拦截的方法开始执行时候调用 /// </summary> /// <param name="invocation"></param> protected override void PerformProceed(IInvocation invocation) { if (invocation.Method.Name.Equals("OnActionExecuting")) { ActionExecutingContext filterContext = (ActionExecutingContext)invocation.GetArgumentValue(0); if (!_authAspect.IsAuthenticationByMvc(filterContext)) { HttpContext.Current.Response.Redirect("", true);//权限认证不通过,跳转到指定页面. return; } } base.PerformProceed(invocation); }
/// <summary> /// 拦截操作 /// </summary> /// <param name="invocation">拦截参数</param> /// <param name="attr">特性</param> /// <param name="isExecProceeded">是否已执行</param> /// <returns>基本返回信息</returns> protected override BasicReturnInfo InterceptOperation(IInvocation invocation, out bool isExecProceeded) { isExecProceeded = false; BasicReturnInfo basicReturn = new BasicReturnInfo(); if (invocation.Arguments.IsNullOrLength0()) { return(basicReturn); } ParameterInfo[] parameters = invocation.Method.GetParameters(); for (var i = 0; i < parameters.Length; i++) { ParameterInfo p = parameters[i]; IEnumerable <Attribute> atts = p.GetCustomAttributes(); if (atts == null) { continue; } DisplayName2Attribute paramDisplayNameAttr = p.GetCustomAttribute <DisplayName2Attribute>(); string displayName = paramDisplayNameAttr == null ? p.Name : paramDisplayNameAttr.Name; foreach (Attribute a in atts) { if (a is ValidationAttribute) { ValidationAttribute v = a as ValidationAttribute; Type type = v.GetType(); if (dicValiParams.ContainsKey(type)) { string errMsg = dicValiParams[type].Exec(invocation.GetArgumentValue(i), v, displayName); if (string.IsNullOrWhiteSpace(errMsg)) { continue; } basicReturn.SetFailureMsg(errMsg); return(basicReturn); } } } } return(basicReturn); }
public void Intercept(IInvocation invocation) { //获取参数 var parameters = new List <object>(); var methodParams = invocation.Method.GetParameters(); for (var iMethodParam = 0; iMethodParam < methodParams.Length; iMethodParam++) { var name = methodParams[iMethodParam].Name; var value = invocation.GetArgumentValue(iMethodParam); parameters.Add(value); } var result = _serviceAdapter.ExecuteServiceAsync(_serviceProvider, invocation.Method, parameters.ToArray()).Result; invocation.ReturnValue = result; }
public void Intercept(IInvocation invocation) { if (!IsApplicable(invocation)) { invocation.Proceed(); } else { invocation.ReturnValue = cache.GetOrAdd((TArg)invocation.GetArgumentValue(0), _ => { invocation.Proceed(); return((TResult)invocation.ReturnValue); } ); } }
public void Intercept(IInvocation invocation) { //Before method execution string key = ""; if (invocation.MethodInvocationTarget.Name == "ReadPost") { key = string.Format("PostDto:Id:{0}", invocation.GetArgumentValue(0).ToString()); } if (invocation.MethodInvocationTarget.Name == "GetAllPost") { key = "AllPosts"; } var Icache = _cacheManager.GetCache("post"); var cache = Icache.GetOrDefault(key); var getResultWay = "Cache"; if (cache == null) { invocation.Proceed(); var type = invocation.Method.ReturnType; var a = typeof(string); //var resultw =( (Task<object>)invocation.ReturnValue ).Result ; var result = invocation.ReturnValue; Icache.Set(key, result); getResultWay = "Database"; } else { invocation.ReturnValue = cache; } //Executing the actual method // invocation.Proceed(); //After method execution _logger.InfoFormat( "{0} executed and return with {1}.", invocation.MethodInvocationTarget.Name, getResultWay); return; }
private string GetCacheKey(IInvocation invocation) { var sb = new StringBuilder(); sb.Append(invocation.Method.Name); sb.Append(";"); ParameterInfo[] parameters = InvocationHelper.MethodParameters(invocation); foreach (var parameter in parameters) { var objectValue = invocation.GetArgumentValue(parameter.Position); string valueHash = EqualityHelper.ValueTypeHashCode(objectValue); sb.Append(valueHash); } return sb.ToString(); //return InvocationHelper.InvocationNameAndArguments(invocation); }
protected override void HandleIntercept(IInvocation invocation) { var message = invocation.GetArgumentValue(0) as HealthCheckResult; var publisher = invocation.InvocationTarget as IHealthCheckResultPublisher; if (Applies(publisher, message)) { // run the filter... if (ShouldPublish(publisher, message)) { invocation.Proceed(); } } else { invocation.Proceed(); } }
public override Task OnError(IInvocation invocation, Exception e) { var logParamters = invocation.MethodInvocationTarget.GetParameters().Select((t, i) => new LogParameter { Name = t.Name, Type = t.ParameterType.Name, Value = invocation.GetArgumentValue(i) }).ToList(); var date = DateTime.Now; var logObj = new LogDetail { FullName = invocation.TargetType.FullName, MethodName = invocation.Method.Name, Parameters = logParamters }; logger.LogInfo(logObj); return(Task.FromResult(Task.CompletedTask)); }
public void Intercept(IInvocation invocation) { var client = new RestClient(GetEndpointUrl()); var request = new RestRequest(GetPath(invocation), DataFormat.Json); int i = 0; foreach (var parameter in invocation.Method.GetParameters()) { request.AddParameter(parameter.Name, invocation.GetArgumentValue(i++)); } var response = client.Post(request); if (invocation.Method.ReturnType != typeof(void)) { invocation.ReturnValue = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content, invocation.Method.ReturnType); } }
/// <summary> /// 执行Http请求接口 /// </summary> /// <param name="invocation">上下文</param> /// <returns></returns> private Task ExecuteHttpApi(IInvocation invocation) { var cache = DescriptorCache.GetApiActionDescriptor(invocation); var actionDescripter = cache.Clone() as ApiActionDescriptor; for (var i = 0; i < actionDescripter.Parameters.Length; i++) { actionDescripter.Parameters[i].Value = invocation.GetArgumentValue(i); } var actionContext = new ApiActionContext { ApiActionDescriptor = actionDescripter, HttpApiConfig = this.httpApiConfig, RequestMessage = new HttpRequestMessage(HttpMethod.Get, this.httpApiConfig.HttpHost), ResponseMessage = null }; return(actionDescripter.Execute(actionContext)); }
public void Intercept(IInvocation invocation) { if (invocation.InvocationTarget is EntityDescriptor) { invocation.Proceed(); return; } var context = invocation.InvocationTarget as IEntityDescriptorContext; if (context == null) { throw new EafException("Cannot read Context from Entity Descriptor Proxy"); } if (invocation.Arguments.Length > 0) { var relationDescriptor = invocation.GetArgumentValue(0); context.RelationDescriptor = (RelationDescriptor)relationDescriptor; } invocation.ReturnValue = context.RelationDescriptor; }
public void Intercept(IInvocation invocation) { ParameterInfo[] paras = invocation.Method.GetParameters(); int argLength = paras.Length; if (argLength > 0) { for (int i = 0; i < argLength; i++) { ParameterInfo para = paras[i]; Type paraType = para.ParameterType; if (paraType == typeof(String)) { string paraOriginalValue = Convert.ToString(invocation.GetArgumentValue(i)); string paraConveredValue = SQLInjectionHelper.GetSafeSqlBeforeSave(paraOriginalValue); invocation.SetArgumentValue(i, paraConveredValue); } } } invocation.Proceed(); }
public void Intercept(IInvocation invocation) { if (!(invocation.InvocationTarget is Device)) { invocation.Proceed(); return; } if (!invocation.Method.Name.StartsWith("set_")) { invocation.Proceed(); return; } var propertyName = invocation.Method.Name.Substring(4); var getterName = "get_" + propertyName; var getter = invocation.TargetType.GetMethod(getterName); if (getter == null) { invocation.Proceed(); return; } if (!getter.IsPublic) { invocation.Proceed(); return; } invocation.Proceed(); var device = (Device)(invocation.InvocationTarget); var command = new SetPropertyCommand(device.Id, Serializer.Resolver.GetResolvedPropertyName(propertyName), invocation.GetArgumentValue(0)); CommandBus.Instance.Publish(command).ContinueWith((obj) => { }); }
//public DataBindingInterceptor(System.Type persistentClass, object id, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, ISessionImplementor session) // : base(persistentClass, id, getIdentifierMethod, setIdentifierMethod, session) //{ //} public override void Intercept(IInvocation invocation) { object result; if (invocation.Method.DeclaringType == typeof (INotifyPropertyChanged)) { var propertyChangedEventHandler = (PropertyChangedEventHandler) invocation.GetArgumentValue(0); if (invocation.Method.Name.StartsWith("add_")) { subscribers += propertyChangedEventHandler; } else { subscribers -= propertyChangedEventHandler; } return; } base.Intercept(invocation); result = invocation.ReturnValue; if (invocation.Method.Name.StartsWith("set_")) { subscribers(this, new PropertyChangedEventArgs(invocation.Method.Name.Substring(4))); } invocation.ReturnValue = result; }
private void HandleSetter(MethodInfo method, IInvocation invocation) { // Find the get method var getter = invocation.TargetType.GetMethod("g" + method.Name.Remove(0, 1)); PropertyValue propValue; if (Properties.TryGetValue(getter, out propValue)) { // Resets the value... propValue.Value = invocation.GetArgumentValue(0); return; } // Sets the value and caches it. propValue = Properties[getter] = new PropertyValue { Value = invocation.GetArgumentValue(0), // If this is a collection field interceptor then the value // returned should allways be considered as loaded. IsLoaded = InterceptCollections }; }