public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var results = input.Arguments.Cast<object>().SelectMany(entity => validator.Validate(entity)); return !results.Any() ? getNext()(input, getNext) //no errors : input.CreateExceptionMethodReturn(new ValidationFailedException(results)); }
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); }
/// <exception cref="SapphireUserFriendlyException"><c>SapphireUserFriendlyException</c>.</exception> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var result = getNext()(input, getNext); if (result.Exception == null) return result; throw new SapphireUserFriendlyException(); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // Before invoking the method on the original target. this.logger.Log( "{0}: Invoking method {1}", DateTime.Now.ToLongTimeString(), input.MethodBase.Name); // Invoke the next behavior in the chain. var result = getNext()(input, getNext); // After invoking the method on the original target. if (result.Exception != null) { this.logger.Log( "{0}: Method {1} threw exception {2}", DateTime.Now.ToLongTimeString(), input.MethodBase.Name, result.Exception.Message); } else { this.logger.Log( "{0}: Method {1} returned {2}", DateTime.Now.ToLongTimeString(), input.MethodBase.Name, result.ReturnValue ?? "void"); } return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { ISession session = SessionFactory.GetCurrentSession(); ITransaction transaction = null; if (IsolationLevel == IsolationLevel.Unspecified) { transaction = session.BeginTransaction(); } else { transaction = session.BeginTransaction(IsolationLevel); } Debug.WriteLine("Started transaction"); IMethodReturn result = getNext()(input, getNext); if (result.Exception != null) { transaction.Rollback(); Debug.WriteLine("Rolled transaction"); } else { transaction.Commit(); Debug.WriteLine("Committed transaction"); } transaction.Dispose(); return result; }
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) { IMethodReturn methodReturn; using (var transaction = this.Factory.GetCurrentSession().BeginTransaction()) { // Here next attribute is called or original method, if no more attributes exist on operation methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null || ShouldCommitDespiteOf(methodReturn.Exception)) { transaction.Commit(); } else { transaction.Rollback(); } } // Required in cases (exceptions>) when instead of normal values NHibernate returns lazy proxies. this.Factory.GetCurrentSession().GetSessionImplementation().PersistenceContext.Unproxy(methodReturn.ReturnValue); // Get back to previous attribute handler or back to caller return methodReturn; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var methodName = input.MethodBase.Name; var target = input.Target; return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Dictionary<Type, Validator> validators = new Dictionary<Type, Validator>(); Int32 i = 0; ValidationResults results = new ValidationResults(); IMethodReturn result = null; foreach (Type type in input.MethodBase.GetParameters().Select(p => p.ParameterType)) { if (validators.ContainsKey(type) == false) { validators[type] = ValidationFactory.CreateValidator(type, this.Ruleset); } Validator validator = validators[type]; validator.Validate(input.Arguments[i], results); ++i; } if (results.IsValid == false) { result = input.CreateExceptionMethodReturn(new Exception(String.Join(Environment.NewLine, results.Select(r => r.Message).ToArray()))); } else { result = getNext()(input, getNext); } return (result); }
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; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (this.Before == true) { String arguments = String.Join(",", input.Arguments.Cast<Object>().Select(a => a != null ? a.ToString() : "null").ToArray()); String beforeMessage = String.Format(this.Message, input.MethodBase, arguments); Logger.Write(beforeMessage, this.Categories, this.Priority, 0, this.Severity); } IMethodReturn result = getNext()(input, getNext); if (result.Exception != null) { if (this.Exception == true) { String afterMessage = String.Format(this.Message, input.MethodBase, result.Exception); Logger.Write(afterMessage, this.Categories, this.Priority, 0, this.Severity); } } else { if (this.After == true) { String afterMessage = String.Format(this.Message, input.MethodBase, result.ReturnValue); Logger.Write(afterMessage, this.Categories, this.Priority, 0, this.Severity); } } return (result); }
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) { if (input.Arguments.Count > 0) { var arguments = new Argument[input.Arguments.Count]; for (int i = 0; i < input.Arguments.Count; i++) { arguments[i] = new Argument { Name = input.Arguments.ParameterName(i), Value = input.Arguments[i] }; } _tape.RecordRequest(arguments, input.MethodBase.ReflectedType, input.MethodBase.Name); } Console.WriteLine("> Intercepting " + input.MethodBase.Name); Console.WriteLine("> Intercepting " + input.MethodBase.ReflectedType); IMethodReturn methodReturn = getNext()(input, getNext); Console.WriteLine("> Intercepted return value: " + methodReturn.ReturnValue.GetType().Name); if (methodReturn.ReturnValue != null) { _tape.RecordResponse(methodReturn.ReturnValue, input.MethodBase.ReflectedType, input.MethodBase.Name); } return methodReturn; }
/// <summary> /// Invokes the specified input. /// </summary> /// <param name="input">The input.</param> /// <param name="getNext">The get next.</param> /// <returns>The method return result.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { foreach (var argument in input.Arguments) { string target = argument as string; if (string.IsNullOrEmpty(target)) { continue; } if (Regex.Match(target, @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").Success) { continue; } ArgumentException argumentException = new ArgumentException("Invalid e-mail format", input.MethodBase.Name); Log.Error("Argument exception", argumentException, this); return input.CreateExceptionMethodReturn(argumentException); } return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { TransactionScope trans; switch (transAttrib.Option) { case TransactinOptionEnum.Required: trans = new TransactionScope(TransactionScopeOption.Required); break; case TransactinOptionEnum.RequiresNew: trans = new TransactionScope(TransactionScopeOption.RequiresNew); break; case TransactinOptionEnum.NotSuppoted: trans = new TransactionScope(TransactionScopeOption.Suppress); break; default: { trans = null; break; } } var result = getNext()(input, getNext); if (trans != null) { trans.Complete(); } return result; //throw new NotImplementedException(); }
/// <summary> /// Implement this method to execute your handler 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 handler chain. /// </param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn methodReturn; try { Stopwatch stopwatch; string className; string methodName; className = input.MethodBase.DeclaringType.Name; methodName = input.MethodBase.Name; stopwatch = new Stopwatch(); stopwatch.Start(); methodReturn = getNext()(input, getNext); stopwatch.Stop(); Debug.WriteLine(string.Format("Executing on object {0} method {1} took: {2}ms", className, methodName, stopwatch.ElapsedMilliseconds)); } catch (Exception exception) { throw; } return methodReturn; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { DbContext dbContext = GetDbContext(input.Target.GetType()); DbConfigurationSupportedCustomExecutionStrategy.SuspendExecutionStrategy = true; using (var transaction = dbContext.Database.BeginTransaction(IsolationLevel.Snapshot)) //using (var transaction = dbContext.Database.BeginTransaction()) { IMethodReturn result = getNext()(input, getNext); if (result.Exception == null) { dbContext.SaveChanges(); transaction.Commit(); } else { _logger.Info(String.Format("Detected exception in transaction. Perform rollback. Exception: {0}", result.Exception.Message), result.Exception); transaction.Rollback(); } DbConfigurationSupportedCustomExecutionStrategy.SuspendExecutionStrategy = false; return result; } }
public IMethodReturn Invoke( IMethodInvocation input, GetNextHandlerDelegate getNext) { if (this.allowedRoles.Length > 0) { IPrincipal currentPrincipal = Thread.CurrentPrincipal; if (currentPrincipal != null) { bool allowed = false; foreach (string role in this.allowedRoles) { if (allowed = currentPrincipal.IsInRole(role)) { break; } } if (!allowed) { // short circuit the call return input.CreateExceptionMethodReturn( new UnauthorizedAccessException( "User not allowed to invoke the method")); } } } return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = getNext()(input, getNext); Thread.Sleep(this.Delay); return (result); }
/// <summary> /// Invokes the Timing Handler /// </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 handler chain.</param> /// <returns>Return value from the target.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var stopwatch = Stopwatch.StartNew(); var result = getNext()(input, getNext); stopwatch.Stop(); publisher.FireEvent(new TimedCallEventArgs(input.Target, input.MethodBase, stopwatch.Elapsed)); return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (input.MethodBase.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(); } return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { User user = input.Inputs[0] as User; if (user.PassWord.Length < 0) { return input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")); } Console.WriteLine("参数检测无误"); return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = getNext()(input, getNext); var args = string.Join(", ", input.Arguments.Cast<object>().Select(x => (x ?? string.Empty).ToString())); Trace.WriteLine(string.Format("Unity: {0}({1})", input.MethodBase.Name, args)); return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = getNext()(input, getNext); if (result.Exception != null) { throw result.Exception; } return result; }
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); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = null; result = getNext()(input, getNext); var returnValue = result.ReturnValue; return result; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { LiquidsHelper.StartTransaction(); var toReturn = getNext()(input, getNext); LiquidsHelper.CommitTransaction(); return toReturn; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var methodReturn = getNext()(input, getNext); if (methodReturn.ReturnValue != null && methodReturn.ReturnValue is string) { methodReturn.ReturnValue = ((string)methodReturn.ReturnValue) + this.Suffix; } return methodReturn; }
/// <summary> /// Handler de invocação do método com atributo /// </summary> /// <param name="input">Informações da chamada</param> /// <param name="getNext">Próximo handler de execução do método</param> /// <returns>Caso estejamos fora dum UoW, retorna exception, caso contrário segue a execução</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (UnitOfWork.Current == null) { return input.CreateExceptionMethodReturn(new Exception("Método " + input.MethodBase.Name + " chamado fora de UnitOfWork.")); } // Retornamos normalmente return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var client = (ApiClient)input.Inputs["client"]; if (client == null) throw new ArgumentException("client"); if (client.Token == null || client.Token.IsInvalid) client.DoAuth(); return getNext()(input, getNext); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // Before invoking the method on the original target WriteLog(String.Format("Invoking method {0} at {1}", input.MethodBase, DateTime.Now.ToLongTimeString())); // Invoke the next handler in the chain var result = getNext().Invoke(input, getNext); // After invoking the method on the original target if (result.Exception != null) { WriteLog(String.Format("Method {0} threw exception {1} at {2}", input.MethodBase, result.Exception.Message, DateTime.Now.ToLongTimeString())); } else { WriteLog(String.Format("Method {0} returned {1} at {2}", input.MethodBase, result.ReturnValue, DateTime.Now.ToLongTimeString())); } return(result); }
protected virtual Func <IMethodReturn> GetSyncReturn(IMethodInvocation input, GetNextHandlerDelegate getNext) { return(() => getNext()(input, getNext)); }
/// <summary> /// 调用方法 实现ICallHandler.Invoke方法,用于对具体拦截方法做相应的处理 /// </summary> /// <param name="input"></param> /// <param name="getNext"></param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { string inParam, outParam; inParam = string.Empty; outParam = string.Empty; //检查参数是否存在 if (input == null) { throw new ArgumentNullException("input"); } if (getNext == null) { throw new ArgumentNullException("getNext"); } string paramName, paramValue; //1.证书, 采用数据签名的方式 //2.如果只有一个入参时, 则进行记录日志操作 for (int i = 0; i < input.Inputs.Count; i++) { ParameterInfo pi = input.Inputs.GetParameterInfo(i); paramName = pi.Name; if (pi.ParameterType == typeof(string)) //找到凭证参数 { paramValue = input.Inputs[i].ToString(); if (paramValue.IsNotNull()) { inParam = inParam + paramName + ":[" + paramValue + "] \r\n"; } } if (pi.ParameterType == typeof(XmlDocument)) { paramValue = ((XmlDocument)input.Inputs[i]).InnerXml; if (paramValue.IsNotNull()) { inParam = inParam + paramName + ":[" + paramValue + "] \r\n"; } } } //3.调用方法 开始拦截,此处可以根据需求编写具体业务逻辑代码 DateTime callTimeStart = DateTime.Now; var result = getNext().Invoke(input, getNext); //4.记录日志 if (inParam.IsNotNull()) { if (result.Outputs.Count > 0) { paramName = "OutParam"; paramValue = result.Outputs[0].ToString(); outParam = outParam + paramName + ":[" + paramValue + "] \r\n"; } DateTime callTimeEnd = DateTime.Now; string introduction = Introduction.IsNull() ? input.MethodBase.ToString() : Introduction; //2.记录日志 if (result.Exception != null) //判断异常并记录异常日志 { WriteAppErrorLog(result.Exception); } else //如果调用方法没有出现异常则记录操作日志 { WriteServiceCallLog(introduction, callTimeStart, callTimeEnd, inParam, outParam); } } //返回方法,拦截结束 return(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // Get personChoice value from object property. personChoice = (PersonChoice)Enum.Parse(typeof(PersonChoice), input.Target.GetType().GetProperty("PersonChoice").GetValue(input.Target, null).ToString()); // Get Method Name and parameters string methodName = input.MethodBase.Name; object[] methodArgs = new object[input.Inputs.Count]; for (int i = 0; i < input.Inputs.Count; i++) { methodArgs[i] = input.Inputs[i]; } Type firstPersonType = null; Type secondPersonType = null; object firstPersonObject; object secondPersonObject; // based on personChoice value, instantiate appropriate class and execute the appropriate method . switch (personChoice) { case PersonChoice.Peter: firstPersonType = typeof(TestClassPeter); break; case PersonChoice.Charles: firstPersonType = typeof(TestClassCharles); break; case PersonChoice.Both: firstPersonType = typeof(TestClassPeter); secondPersonType = typeof(TestClassCharles); break; default: break; } // object is instantiated with default constructor. No need to specify PersonChoice property. firstPersonObject = Activator.CreateInstance(firstPersonType); if (personChoice == PersonChoice.Both) { secondPersonObject = Activator.CreateInstance(secondPersonType); } else { secondPersonObject = null;; } // decide method invocation based on PersonChoice object firstReturnValue; object secondReturnValue; switch (personChoice) { // Call Peter's or Charles' methods case PersonChoice.Peter: case PersonChoice.Charles: firstReturnValue = firstPersonType.InvokeMember(methodName, BindingFlags.InvokeMethod, null, firstPersonObject, methodArgs); break; // Call Method on Both Peter and Charles and combine results case PersonChoice.Both: firstReturnValue = firstPersonType.InvokeMember(methodName, BindingFlags.InvokeMethod, null, firstPersonObject, methodArgs); secondReturnValue = secondPersonType.InvokeMember(methodName, BindingFlags.InvokeMethod, null, secondPersonObject, methodArgs); // build return value. Done here checking method name as an example. if (methodName == "NamePlusLastName") { string returnValue = (string)firstReturnValue; firstReturnValue = returnValue + (string)secondReturnValue; } else { int returnValue = (int)firstReturnValue; firstReturnValue = returnValue + (int)secondReturnValue; } break; default: firstReturnValue = firstPersonType.InvokeMember(methodName, BindingFlags.InvokeMethod, null, firstPersonObject, methodArgs); break; } // Override initial method execution IMethodReturn methodReturn = new VirtualMethodReturn(input, null); // this down here would have called the original method. //var methodReturn = getNext().Invoke(input, getNext); // Set the return value methodReturn.ReturnValue = firstReturnValue; return(methodReturn); }
public abstract IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext);
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var returnMessage = getNext()(input, getNext); if (returnMessage.Exception == null) { EyouSoft.BusinessLogWriter.Model.LogWriter model = new EyouSoft.BusinessLogWriter.Model.LogWriter(); model.EventCode = this.EventCode; #region 操作结果判断 if (returnMessage.ReturnValue is int && (int)returnMessage.ReturnValue != 1) { LogMessage = "操作失败"; model.EventCode = this.ErrorCode; EventOK = false; } else if (returnMessage.ReturnValue is bool && !(bool)returnMessage.ReturnValue) { LogMessage = "操作失败"; model.EventCode = this.ErrorCode; EventOK = false; } else if (returnMessage.ReturnValue is EyouSoft.Model.ResultStructure.ResultInfo && (int)returnMessage.ReturnValue != 1) { LogMessage = "操作失败"; model.EventCode = this.ErrorCode; EventOK = false; } else if (returnMessage.ReturnValue is EyouSoft.Model.ResultStructure.UserResultInfo && (int)returnMessage.ReturnValue != 1) { LogMessage = "操作失败"; model.EventCode = this.ErrorCode; EventOK = false; } #endregion #region 日志内容拼接 if (EventOK && LogAttribute != null) { foreach (LogAttribute attribute in this.LogAttribute) { object obj = new object(); if (attribute.AttributeType == "class") { Type ArguType = input.Arguments[attribute.Index].GetType(); System.Reflection.PropertyInfo pis = ArguType.GetProperty(attribute.Attribute); if (pis != null) { obj = pis.GetValue(input.Arguments[attribute.Index], null); } } else if (attribute.AttributeType == "array") { string logArug = ""; if (input.Arguments[attribute.Index] is int[]) { int[] target = (int[])input.Arguments[attribute.Index]; foreach (int arg in target) { logArug += arg.ToString() + ","; } } else { object[] target = (object[])input.Arguments[attribute.Index]; foreach (object arg in target) { logArug += arg.ToString() + ","; } } if (logArug.EndsWith(",")) { logArug = logArug.Substring(0, logArug.Length - 1); } obj = logArug.ToString(); } else { obj = input.Arguments[attribute.Index].ToString(); } LogMessage = LogMessage.Replace("{" + i + "}", obj.ToString()); i++; } } #endregion if (!(LogWriter is EyouSoft.BusinessLogWriter.WebMasterLog)) { EyouSoft.SSOComponent.Entity.UserInfo UserInfo = null; if (UserInfo == null) { UserInfo = EyouSoft.Security.Membership.UserProvider.GetUser(); } if (UserInfo == null) { UserInfo = new EyouSoft.Security.Membership.UserProvider().GetMQUser(); } model.CompanyId = ""; model.OperatorId = ""; model.OperatorName = ""; if (UserInfo != null) { model.CompanyId = UserInfo.CompanyID; model.OperatorId = UserInfo.ID; model.OperatorName = UserInfo.UserName; } } else if (LogWriter is EyouSoft.BusinessLogWriter.WebMasterLog) { EyouSoft.SSOComponent.Entity.MasterUserInfo MasterUserInfo = new EyouSoft.Security.Membership.UserProvider().GetMaster(); if (MasterUserInfo != null) { model.CompanyId = string.Empty; model.OperatorId = MasterUserInfo.ID.ToString(); model.OperatorName = MasterUserInfo.UserName; } } model.EventTitle = this.LogTitle; if (EventOK) { model.EventMessage = this.LogMessage.Replace("[人员]", model.OperatorName).Replace("[时间]", DateTime.Now.ToString()); } else { model.EventMessage = LogMessage; } model.EventIP = EyouSoft.Common.Utility.GetRemoteIP(); model.EventUrl = EyouSoft.Common.Utility.GetRequestUrl(); model.EventID = System.Guid.NewGuid().ToString(); model.EventTime = DateTime.Now; LogWriter.WriteLog(model); } return(returnMessage); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var cacheKey = _keyGenerator.GenerateKey(input); var methodIsTask = input.MethodBase.IsGenericTask(); var returnType = input.MethodBase.GetReturnType(); var cachedResult = typeof(ICache).GetMethod("Get") .MakeGenericMethod(returnType) .Invoke(_cache, new object[] { cacheKey }); object unwrappedResult = null; var scheduleDurableRefresh = false; //Force cache miss for durable results that are behind if (cachedResult != null && AbsoluteExpiration != null) { var lastUpdate = (DateTime)CacheExtensions.GetLastUpdate((dynamic)cachedResult); var expires = (DateTime)CacheExtensions.GetExpires((dynamic)cachedResult); if (DateTime.UtcNow.Subtract(lastUpdate).TotalSeconds > MaximumStaleness.TotalSeconds) { if (RescheduleStale && DateTime.UtcNow.Add(Expiration) < expires) { scheduleDurableRefresh = true; } else { cachedResult = null; } } } // Nothing is cached for this method if (cachedResult == null) { // Get a new result var newResult = getNext()(input, getNext); //Do not cache exceptions if (newResult.Exception == null) { if (methodIsTask) { newResult.ReturnValue = (dynamic)typeof(CacheExtensions).GetMethod("AddToCacheAsync") .MakeGenericMethod(returnType) .Invoke(null, new object[] { _cache, newResult.ReturnValue, cacheKey, DateTime.UtcNow.Add(AbsoluteExpiration ?? Expiration) }); } else { typeof(CacheExtensions).GetMethod("AddToCache") .MakeGenericMethod(returnType) .Invoke(null, new object[] { _cache, newResult.ReturnValue, cacheKey, DateTime.UtcNow.Add(AbsoluteExpiration ?? Expiration) }); } //queue refresh if configured by the user scheduleDurableRefresh = AbsoluteExpiration != null; } unwrappedResult = newResult.ReturnValue; } else { if (methodIsTask) { var unwrappedResultMissingTask = CacheExtensions.Unwrap((dynamic)cachedResult); unwrappedResult = typeof(Task).GetMethod("FromResult") .MakeGenericMethod(input.MethodBase.GetGenericReturnTypeArguments()) .Invoke(null, new object[] { unwrappedResultMissingTask }); } else { unwrappedResult = CacheExtensions.Unwrap((dynamic)cachedResult); } } if (scheduleDurableRefresh) { var parameters = new object[input.Inputs.Count]; input.Inputs.CopyTo(parameters, 0); var queue = _container.Resolve <IDurableCacheQueue>(); queue.ScheduleRefresh(new DurableCacheRefreshEvent { AbsoluteExpiration = AbsoluteExpiration.Value, CacheName = _cacheName, Key = cacheKey, Method = new DurableMethod { DeclaringType = input.Target.GetType(), Interface = input.MethodBase.DeclaringType, Name = input.MethodBase.Name, Parameters = input.MethodBase.GetParameters() .Select(p => p.ParameterType).ToArray() }, Parameters = parameters, RefreshTime = Expiration, UtcLifetime = cachedResult != null ? (DateTime)CacheExtensions.GetExpires((dynamic)cachedResult) : DateTime.UtcNow.Add(AbsoluteExpiration.Value), }); } var arguments = new object[input.Inputs.Count]; input.Inputs.CopyTo(arguments, 0); return(new VirtualMethodReturn(input, unwrappedResult, arguments)); }
public IMethodReturn Invoke(IMethodInvocation call, GetNextHandlerDelegate getNext) { return(new StubMethodReturn()); }
public override IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { return(_dispatcher.Dispatch(GetSyncReturn(input, getNext), GetAsyncReturn(input, getNext))); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { CacheMode cacheMode = GetCacheMode(input.MethodBase); ICacheAPI cacheAPI = ChooseCacheAPI(cacheMode); if (cacheAPI == null) { logger.Error("No cache used"); return(getNext()(input, getNext)); } string cacheImplName = cacheAPI.GetType().Name; cacheAPI = new CacheProxy(cacheAPI, cacheMode, cacheStatistics); CacheType cacheType = GetCacheType(input.MethodBase); string cacheGroup = GetCacheGroup(input.MethodBase); string cacheKey = CreateCacheKey(input.MethodBase, input.Arguments); logger.Info(string.Format("Choose cache api as {0}, cacheGroup={1}, cacheKey={2}", cacheImplName, cacheGroup, cacheKey)); if (cacheMode.Equals(CacheMode.REMOTE) && cacheStatistics.IsError(cacheMode, cacheGroup)) { logger.Error("Remote cache error occured too many, skip cache, get data from DB."); return(getNext()(input, getNext)); } if (CacheType.FETCH.Equals(cacheType)) { object obj = null; try { obj = cacheAPI.Get(cacheGroup, cacheKey); } catch (Exception ex) { logger.Error("get cache failed, cachetype=" + cacheType, ex); return(getNext()(input, getNext)); } if (obj != null) { logger.Info("Hitting cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); cacheStatistics.AddHitCount(cacheMode, cacheGroup); return(input.CreateMethodReturn(obj, null)); } else { cacheStatistics.AddUnhitCount(cacheMode, cacheGroup); IMethodReturn methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null && methodReturn.ReturnValue != null) { cacheAPI.Add(cacheGroup, cacheKey, methodReturn.ReturnValue); logger.Info("Adding into cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); } return(methodReturn); } } else if (CacheType.CLEAR.Equals(cacheType)) { IMethodReturn methodReturn = getNext()(input, getNext); cacheAPI.Remove(cacheGroup, cacheKey); return(methodReturn); } else if (CacheType.UPDATE.Equals(cacheType)) { object cacheValue = GetCacheValue(input.Arguments); if (cacheValue != null) { cacheAPI.Update(cacheGroup, cacheKey, cacheValue); logger.Info("Update cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); } return(getNext()(input, getNext)); } else { logger.Error("Invalid cache type, cachetype=" + cacheType); return(getNext()(input, getNext)); } }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = getNext()(input, getNext); WriteLog($"Method {input.MethodBase} {(result.Exception != null ? $"threw exception {result.Exception.Message}" : $"returns {result.ReturnValue}")} at {DateTime.Now.ToLongTimeString()}");
private static IMethodReturn Proceed(IMethodInvocation input, GetNextHandlerDelegate getNext) { return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.Write("Hello, "); return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = getNext()(input, getNext); return(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result = input.CreateMethodReturn(null); return(result); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { throw new Exception("The method or operation is not implemented."); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.WriteLine("LoggerAttribute"); return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn msg = null; TraceContext context = null; if (ApplicationContext.Current != null) { context = TraceContext.GetContext( ApplicationContext.Current.UserId, ApplicationContext.Current.TerminalId, ApplicationContext.Current.SessionId); } if (context != null && context.IsTracingEnabled) { lock (context) { using (ITransactionScope scope = new TransactionScope()) { string userId = context.UserId; if ((userId.Contains('\\') || userId.Contains('/'))) { string[] userIdParts = userId.Split(new char[] { '\\', '/' }); userId = userIdParts[1]; } ITracingDao tracingDao = new TracingDao(connectionString); StartDatabaseTracingParameters startParameters = new StartDatabaseTracingParameters(); startParameters.TerminalId = context.TerminalId; startParameters.UserId = userId; startParameters.WriteHeader = false; tracingDao.StartDatabaseTracing(startParameters); try { msg = getNext()(input, getNext); } finally { StopDatabaseTracingParameters stopParameters = new StopDatabaseTracingParameters(); stopParameters.WriteHeader = false; tracingDao.StopDatabaseTracing(stopParameters); } try { scope.Complete(); } catch (InvalidOperationException) { } } } } else { msg = getNext()(input, getNext); } return(msg); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { CacheMeta cacheMeta = cacheMetaLoader.Load(input.MethodBase); if (cacheMeta == null) { logger.Error("CacheMeta is null", new ArgumentNullException()); return(getNext()(input, getNext)); } CacheMode cacheMode = cacheMeta.CacheMode; ICacheHelper cacheHelper = ChooseCacheHelper(cacheMode); if (cacheHelper == null) { logger.Error(cacheMode + "cache type not found", new CacheModeNotFoundException()); return(getNext()(input, getNext)); } cacheHelper = new CacheProxy(cacheMode, cacheHelper); CacheAction cacheAction = cacheMeta.CacheAction; string cacheKey = BuildCacheKey(cacheMeta, input.Arguments); string groupName = cacheMeta.CacheGroup; string cacheType = cacheHelper.GetType().Name; logger.Debug(string.Format("Choose {0} as cache helper, cacheGroup={1}, cacheKey={2}", cacheType, cacheMeta.CacheGroup, cacheKey)); if (cacheAction == CacheAction.FETCH) { object obj; try { obj = cacheHelper.Get(groupName, cacheKey); } catch (Exception ex) { logger.Error("Get cache failed, cacheType=" + cacheType, ex); return(getNext()(input, getNext)); } if (obj != null) { logger.Debug(string.Format("Hitting cache, cacheGroup={0}, cacheKey={1}", groupName, cacheKey)); return(input.CreateMethodReturn(obj, null)); } else { IMethodReturn methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null && methodReturn.ReturnValue != null) { cacheHelper.Add(groupName, cacheKey, methodReturn.ReturnValue); logger.Info(string.Format("Adding to cache, cacheGroup={0}, cacheKey={1}", groupName, cacheKey)); } return(methodReturn); } } else if (cacheAction == CacheAction.UPDATE) { object cacheValue = GetCacheValue(input.Arguments); if (cacheValue != null) { cacheHelper.Update(groupName, cacheKey, cacheValue); logger.Info(string.Format("Update cache, cacheGroup={0}, cacheKey={1}", groupName, cacheKey)); } return(getNext()(input, getNext)); } else if (cacheAction == CacheAction.CLEAR) { IMethodReturn methodReturn = getNext()(input, getNext); cacheHelper.Remove(groupName, cacheKey); logger.Info(string.Format("Remove cache, cacheGroup={0}, cacheKey={1}", groupName, cacheKey)); return(methodReturn); } return(getNext()(input, getNext)); }
/// <summary> /// Implement this method to execute your handler 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 handler /// chain.</param> /// <returns>Return value from the target.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Log(Id, "invoked method " + input.MethodBase.DeclaringType.FullName + input.MethodBase.Name); return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { InterceptionCount++; return(getNext.Invoke().Invoke(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { InvokeHandlerDelegate next = getNext(); return(next(input, getNext)); }
//************************************************************************ /// <summary> /// メソッドの実行中カーソルを処理中に変更する。 /// </summary> /// <param name="input">IMethodInvocation</param> /// <param name="getNext">GetNextHandlerDelegate</param> /// <returns>IMethodReturn</returns> //************************************************************************ public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn returnMessage = null; // フォームを取得 var form = (Form)input.Target; // 画面IDを設定 InformationManager.ClientInfo.FormId = form.GetType().BaseType.Name; // フォーム操作不可 form.Enabled = false; // カーソルを処理中に変更 var orgCursor = form.Cursor; form.Cursor = Cursors.WaitCursor; // メソッド実行 returnMessage = getNext()(input, getNext); // フォームをアクティブにする form.Activate(); // 処理中に溜まったイベントを処理 Application.DoEvents(); // カーソルを戻す form.Cursor = orgCursor; // フォーム操作可 form.Enabled = true; // 例外処理 if (returnMessage.Exception != null) { ApplicationMessage message; if (returnMessage.Exception is FaultException <ApplicationMessage> ) { var faultEx = returnMessage.Exception as FaultException <ApplicationMessage>; message = faultEx.Detail; m_logger.Error(message, faultEx); } else if (returnMessage.Exception is FaultException <ExceptionDetail> ) { var faultEx = returnMessage.Exception as FaultException <ExceptionDetail>; message = new ApplicationMessage("EV001", GetDialogMessage(faultEx.Detail)); m_logger.Error(message, faultEx); } else { // 業務エラーの場合 if (returnMessage.Exception is BusinessException) { message = ((BusinessException)returnMessage.Exception).ApplicationMessage; } // その他の場合 else { string msgCd = "EV001"; if (returnMessage.Exception is FileNotFoundException) { msgCd = "W"; } else if (returnMessage.Exception is IOException) { msgCd = "EV003"; } message = new ApplicationMessage(msgCd, CommonUtil.GetExceptionMessage(returnMessage.Exception)); } m_logger.Error(message, returnMessage.Exception); } CustomMessageBox.Show(message); returnMessage.Exception = null; } return(returnMessage); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.WriteLine("<<<Test>>> {0}:: {1}", input.Target, input.MethodBase); return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // do stuff ... // then return(getNext()(input, getNext)); }
public IMethodReturn Invoke(IMethodInvocation __方法, GetNextHandlerDelegate __获取嵌套方法) { if (__方法.MethodBase.IsDefined(typeof(NoLogAttribute), false)) { return(__获取嵌套方法()(__方法, __获取嵌套方法)); } var __执行前 = new StringBuilder(); var __缩进 = ""; for (int i = 0; i < Order; i++) { __缩进 += _缩进; } var __函数 = string.Format("[{0}] {1} : {2}", Order, 获取原始类(__方法.Target), __方法.MethodBase); __执行前.Append(__缩进).Append(__函数); var __输入参数数量 = __方法.Arguments.Count; for (int i = 0; i < __输入参数数量; i++) { if (i == 0) { __执行前.AppendLine(" || "); } var __参数 = __方法.Arguments[i]; if (__输入参数数量 == 1) { __执行前.Append(__缩进).Append(_缩进).AppendFormat("输入{0} : {1}", i + 1, __参数); } else { __执行前.Append(__缩进).Append(_缩进).AppendFormat("输入{0}/{2} : {1}", i + 1, __参数, __输入参数数量); } if (i != __输入参数数量 - 1) { __执行前.AppendLine(); } } 输出(__执行前.ToString()); Order++; IMethodReturn __结果 = __获取嵌套方法()(__方法, __获取嵌套方法); Order--; __缩进 = ""; for (int i = 0; i < Order; i++) { __缩进 += _缩进; } var __执行后 = new StringBuilder(); if (__结果.ReturnValue != null) { __执行后.Append(__缩进).Append(_缩进).AppendLine("结果 : " + __结果.ReturnValue); } var __输出参数数量 = __结果.Outputs.Count; for (int i = 0; i < __输出参数数量; i++) { var __参数 = __结果.Outputs[i]; if (__输出参数数量 == 1) { __执行后.Append(__缩进).Append(_缩进).AppendFormat("输出{0} : {1}", i + 1, __参数).AppendLine(); } else { __执行后.Append(__缩进).Append(_缩进).AppendFormat("输出{0}/{2} : {1}", i + 1, __参数, __输出参数数量).AppendLine(); } } if (__结果.Exception != null) { __执行后.AppendFormat("异常 : [{0}] {1}", __结果.Exception.GetType(), __结果.Exception.Message); __执行后.AppendLine().Append(Environment.StackTrace); } if (__执行后.Length > 0) { __函数 = string.Format("[{0}] {1} : {2} || {3}", Order, 获取原始类(__方法.Target), __方法.MethodBase, Environment.NewLine); __执行后.Insert(0, __函数).Insert(0, __缩进); 输出(__执行后.ToString().Remove(__执行后.Length - 1)); } return(__结果); }
protected virtual Func <IMethodReturn> GetAsyncReturn(IMethodInvocation input, GetNextHandlerDelegate getNext) { return(() => input.CreateMethodReturn(null, input.Arguments.Cast <object>().ToArray())); }
public override IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { throw new NotImplementedException(); }
public override IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { using (Hole.OfTry(() => CreateRecord(input), HangingMonitor.BeginMonitor, HangingMonitor.EndMonitor)) return(getNext()(input, getNext)); }