/// <summary> /// Invoke the delegate with the provided parameters.<br></br> /// The method must be static /// </summary> /// <returns></returns> public object Invoke(object instance, params object[] parameters) { if ((instance == null) && ((Access & AccessModifiers.Static) == 0)) { throw new ArgumentNullException(nameof(instance), "Can not read value without a new instance"); } var parameterCount = ParameterCount; if (parameters.Length >= parameterCount) { return(InvokeDelegate.Invoke(instance, parameters)); } var oldParameters = parameters; parameters = new object[parameterCount]; for (var i = oldParameters.Length + 1; i < parameterCount; i++) { var parameterInfo = Parameters[i]; if (parameterInfo.IsOptional == false) { throw new ArgumentException("Not enough parameters", nameof(parameters)); } parameters[i] = parameterInfo.DefaultValue; } oldParameters.CopyTo(parameters, 0); return(InvokeDelegate.Invoke(instance, parameters)); }
/// <summary> /// Ivoke the state method on the given target if the state has one /// </summary> public void Invoke(object target, float time) { if (InvokeWithTimeDelegate != null) { InvokeWithTimeDelegate.Invoke(target, time); } else if (InvokeDelegate != null) { InvokeDelegate.Invoke(target); } }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Expression <Func <object> > _function = context.Request.Function; object _instance = context.Request.Instance; var timer = Stopwatch.StartNew(); if (_instance == null) { throw new Exception("Service is null!"); } var fbody = _function.Body as MethodCallExpression; if (fbody == null || fbody.Method == null) { throw new Exception("Expression must be a method call."); } string methodName = fbody.Method.Name; dynamic result = null; List <object> args = new List <object>(); foreach (var argument in fbody.Arguments) { var constant = argument as ConstantExpression; if (constant != null) { args.Add(constant.Value); } } try { result = fbody.Method.Invoke(_instance, args.ToArray <object>()); Type t = context.Result.ResultType; context.Result.Value = result; } catch (Exception e) { throw e; } finally { timer.Stop(); Console.WriteLine($"{methodName}() method invoked in :{Convert.ToDouble(timer.ElapsedMilliseconds)}ms "); } await _next.Invoke(context); }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Console.WriteLine("Begin LoggerManager."); await _next.Invoke(context); Console.WriteLine("End LoggerManager."); }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } object result; result = context.Request.Function.Compile()(); context.Result.Value = result; await _next.Invoke(context); }
/// <summary> /// 条件中间件 /// </summary> /// <typeparam name="TContext"></typeparam> /// <param name="builder"></param> /// <param name="predicate"></param> /// <param name="handler"></param> /// <returns></returns> public static IPipelineBuilder <TContext> When <TContext>(this IPipelineBuilder <TContext> builder, Func <TContext, bool> predicate, InvokeDelegate <TContext> handler) { return(builder.Use(next => async context => { if (predicate.Invoke(context) == true) { await handler.Invoke(context); } else { await next(context); } })); }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ServiceContext serviceContext = context.Request.Properties["ServiceContext"] as ServiceContext; MethodCallExpression fbody = context.Request.MethodCallExpression; if (fbody == null) { throw new ServiceException("Expression must be a method call."); } MethodInfo methodInfo = (MethodInfo)context.Request.Properties["MethodInfo"]; object[] customAttributes = (object[])context.Request.Properties["CustomAttributes"]; if (customAttributes == null) { throw new ArgumentNullException("Service Interface method"); } Authorized authorizedAttributes = customAttributes.FirstOrDefault(t => t.GetType() == typeof(Authorized)) as Authorized; bool checkAuthorization = false; object[] classAttributes = (object[])context.Request.Properties["CustomClassAttributes"]; Authorized classAttribute = classAttributes.FirstOrDefault(t => t.GetType() == typeof(Authorized)) as Authorized; if (classAttribute != null) { checkAuthorization = true; } if (authorizedAttributes == null) { checkAuthorization = false; } if (checkAuthorization && !authorizationService.isAuthorized(authorizedAttributes, serviceContext)) { throw new ServiceException($"Unauthorized access, Method: {context.Request.ServiceInstance.GetType().Name}.{methodInfo.Name}"); } else { await _next.Invoke(context); } }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MethodCallExpression fbody = context.Request.MethodCallExpression; if (fbody == null) { throw new ServiceException("Expression must be a method call."); } await _next.Invoke(context); }
/// <summary> /// 主入口 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(TContext context) { string requestPath = GetRequestPath(context); //路径为"/"时变为类"/Index.html" if (requestPath.Length == 1) { requestPath = defaultUrl; } string actionKey; int shortActionKeyLength; //获取actionKey if (debug) { actionKey = NFinal.Url.ActionKey.GetActionKey(GetRequestMethod(context), requestPath, out shortActionKeyLength); } else { actionKey = NFinal.Url.ActionKey.GetActionKey(GetRequestMethod(context), requestPath, out shortActionKeyLength); } bool hasError = false; NFinal.Action.ActionData <TContext, TRequest> actionData; if (actionFastDic.TryGetValue(actionKey, actionKey.Length, out actionData)) { TRequest request = default(TRequest); try { request = GetRequest(context); } catch { hasError = true; if (actionData.plugConfig.customErrors.mode == Config.Plug.CustomErrorsMode.Off) { using (IAction <TContext, TRequest> controller = GetAction(context, actionData.plugConfig)) { controller.Initialization(context, actionData.methodName, null, request, CompressMode.GZip, actionData.plugConfig); controller.SetResponseHeader("Content-Type", "text/html; charset=utf-8"); //解析出错 controller.SetResponseStatusCode(200); controller.Close(); } } } NameValueCollection parameters = GetParameters(request); //获取Url中的参数 if (actionData.actionUrlData != null && !actionData.actionUrlData.hasNoParamsInUrl) { if (actionData.actionUrlData.isSimpleUrl) { NFinal.Url.ActionUrlHelper.SimpleParse(requestPath, parameters, actionData.actionUrlData.actionUrlNames, shortActionKeyLength, actionData.actionUrlData.extensionLength); } else { NFinal.Url.ActionUrlHelper.RegexParse(requestPath, parameters, actionData.actionUrlData.actionUrlNames, actionData.actionUrlData.parameterRegex); } } //生产环境下 if (!debug) { if (!NFinal.Filter.FilterHelper.ParamaterFilter(actionData.IParametersFilters, parameters)) { await FinishedTask; } try { actionData.actionExecute(context, actionData, request, parameters); } catch (Exception) { hasError = true; if (actionData.plugConfig.customErrors.mode == Config.Plug.CustomErrorsMode.Off) { using (IAction <TContext, TRequest> controller = GetAction(context, actionData.plugConfig)) { controller.Initialization(context, null, null, request, CompressMode.GZip, actionData.plugConfig); controller.SetResponseHeader("Content-Type", "text/html; charset=utf-8"); //服务器错误 controller.SetResponseStatusCode(500); controller.Close(); } } } if (hasError) { using (IAction <TContext, TRequest> controller = GetAction(context, actionData.plugConfig)) { controller.Initialization(context, null, null, request, CompressMode.GZip, actionData.plugConfig); controller.Redirect(actionData.plugConfig.customErrors.defaultRedirect); } } } //测试环境下 else { //actionData.actionExecute(context, actionData, request, parameters); try { actionData.actionExecute(context, actionData, request, parameters); } catch (System.Exception e) { #region 输出错误信息 using ( IAction <TContext, TRequest> controller = GetAction(context, actionData.plugConfig)) { controller.SetResponseHeader("Content-Type", "text/html; charset=utf-8"); controller.SetResponseStatusCode(200); controller.Write("错误消息:<br/>"); controller.Write(e.Message); controller.Write("<br/>"); controller.Write("请求时发生错误:<br>"); controller.Write(GetRequestPath(context)); controller.Write("<br/>"); controller.Write("错误跟踪:</br>"); string[] stackTraces = e.StackTrace.Split('\n'); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\s+at\s([\S\s]+)(\sin\s([\S\s]+):line\s([0-9]+))+?\s*"); System.Text.RegularExpressions.Match mat; string atfunctionName; string infilePostion; string fileName; int lineNum; string fileText; int currentLineNum; controller.Write("<html>"); controller.Write("<head></head>"); controller.Write("<body>"); controller.Write("<div id=\"traces\">"); for (int i = 0; i < stackTraces.Length; i++) { controller.Write("<dl>"); mat = reg.Match(stackTraces[i]); controller.Write("<dt style=\"background:grey;cursor:pointer;\">"); controller.Write(stackTraces[i]); controller.Write("</dt>"); if (i == 0) { controller.Write("<dd style=\"display: block;\">"); } else { controller.Write("<dd style=\"display: none;\">"); } if (mat.Success) { atfunctionName = mat.Groups[1].Value; //controller.Write(atfunctionName); if (mat.Groups[2].Success) { infilePostion = mat.Groups[2].Value; fileName = mat.Groups[3].Value; int.TryParse(mat.Groups[4].Value, out lineNum); controller.Write(fileName); controller.Write("<br/>"); using (StreamReader reader = File.OpenText(fileName)) { currentLineNum = 0; controller.Write("<ul style=\"list-style:none;\">"); while (!reader.EndOfStream) { currentLineNum++; fileText = reader.ReadLine(); if (currentLineNum == lineNum) { controller.Write("<li style=\"background:red;min-width:500px;\">"); } else { controller.Write("<li>"); } controller.Write(string.Format("{0:0000}", currentLineNum)); controller.Write(":"); if (currentLineNum == lineNum) { controller.Write(fileText.Replace("<", "<") .Replace(">", ">") .Replace("\t", "    ").Replace(" ", " ")); } else { controller.Write(fileText.Replace("<", "<") .Replace(">", ">") .Replace("\t", "    ").Replace(" ", " ")); } controller.Write("</li>"); //controller.Write("<br/>"); } controller.Write("</ul>"); } } else { controller.Write(atfunctionName); } } controller.Write("</dd>"); controller.Write("</dl>"); } controller.Write("</div>"); controller.Write("</body>"); controller.Write("</html>"); controller.Write(@"<script> var tracesDiv = document.getElementById('traces'); var traceTitles = tracesDiv.getElementsByTagName('dt'); for (var i = 0; i < traceTitles.length; i++) { traceTitles[i].addEventListener('click',function() { if (this.nextSibling.style.display == 'none') { this.nextSibling.style.display = 'block'; } else { this.nextSibling.style.display = 'none'; } }); } </script>"); controller.Close(); } #endregion await FinishedTask; } } await FinishedTask; } else { await _next.Invoke(context); } }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ServiceContext serviceContext = context.Request.Properties["ServiceContext"] as ServiceContext; MethodCallExpression fbody = context.Request.MethodCallExpression; if (fbody == null) { throw new ServiceException("Expression must be a method call."); } MethodInfo methodInfo = (MethodInfo)context.Request.Properties["MethodInfo"]; var timer = Stopwatch.StartNew(); try { await _next.Invoke(context); } catch (ServiceException sx) { log.Debug($"{methodInfo.Name}(): {sx.Message}"); throw sx; } catch (Exception ex) { /* ExceptionMiddleware de yapilacak * if (ex.InnerException != null) * { * if (!ex.InnerException.Message.StartsWith(MessagesConstants.ERR_ORA_00001) && * !ex.InnerException.Message.StartsWith(MessagesConstants.ERR_ORA_01407) && * !ex.InnerException.Message.StartsWith(MessagesConstants.ERR_ORA_12899) && * !ex.InnerException.Message.StartsWith(MessagesConstants.ERR_ORA_1722) * ) * { * * Console.WriteLine(ex); * if (Application.Current.Context.GetItem<string>("ENVIRONMENT_NAME") != "Development") * throw new Exception("Servis erişiminde hata oluştu, lütfen bir süre sonra tekrar deneyiniz."); * * } * } */ log.Error(ex); throw ex; } finally { timer.Stop(); if (timer.ElapsedMilliseconds > 1000) { if (isLog4NetEnabled) { log.Debug($"Long method invokation time in { methodInfo.Name} took {timer.ElapsedMilliseconds} ms"); } else { Console.WriteLine($"Long method invokation time in { methodInfo.Name} took {timer.ElapsedMilliseconds} ms"); } } else { if (isLog4NetEnabled) { log.Debug($"{methodInfo.Name}() method invoked in :{Convert.ToDouble(timer.ElapsedMilliseconds)}ms {serviceContext?.UserInfo?.Username} requestId:{serviceContext?.RequestID}"); } else { Console.WriteLine($"{methodInfo.Name}() method invoked in :{Convert.ToDouble(timer.ElapsedMilliseconds)}ms {serviceContext?.UserInfo?.Username} requestId:{serviceContext?.RequestID}"); } } logAuditAsync(); } }
public static void Invoke(MbEvent <T1, T2, T3, T4, T5, T6> instance, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) { Delegate?.Invoke(instance, t1, t2, t3, t4, t5, t6); }
public static void Invoke(MbEvent <T1, T2, T3, T4> instance, T1 t1, T2 t2, T3 t3, T4 t4) { Delegate?.Invoke(instance, t1, t2, t3, t4); }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MethodCallExpression fbody = context.Request.MethodCallExpression; //Putting MethodInfo to context object methodInfoTemp = null; if (!context.Request.Properties.TryGetValue("MethodInfo", out methodInfoTemp)) { methodInfoTemp = fbody.Method; context.Request.Properties["MethodInfo"] = (MethodInfo)methodInfoTemp; } MethodInfo methodInfo = (MethodInfo)methodInfoTemp; //Putting ServiceContext to context object serviceContextTemp = null; if (!context.Request.Properties.TryGetValue("ServiceContext", out serviceContextTemp)) { //TODO : atilla dymaic objeden alinacak var serviceContext = context.Request?.ServiceInstance.GetType()?.GetProperty("ServiceContext"); if (serviceContext != null) { context.Request.Properties["ServiceContext"] = (ServiceContext)serviceContext.GetValue(context.Request.ServiceInstance); } } //Putting Interfaces to cache and context object _interfaceTemp = null; string serviceTypeName = context.Request.ServiceInstance.GetType().Name; if (!Cache("Interface").TryGetValue(serviceTypeName, out _interfaceTemp)) { if (context.Request.ServiceInstance.GetType().GetInterfaces().Count() > 1) { _interfaceTemp = context.Request.ServiceInstance.GetType().GetInterfaces()[1]; Cache("Interface")[serviceTypeName] = _interfaceTemp; } } if (_interfaceTemp != null) { context.Request.Properties["Interface"] = (Type)_interfaceTemp; } //Putting Custom attribute to cache and context object _customAttributesTemp = null; string customAttributeKey = $"{serviceTypeName}.{methodInfo.Name}"; if (!Cache("CustomAttributes").TryGetValue(customAttributeKey, out _customAttributesTemp)) { if (context.Request.Properties.Keys.Contains("Interface")) { Type _interface = (Type)context.Request.Properties["Interface"]; Type _int = (Type)_interface; _customAttributesTemp = _int.GetMethod(methodInfo.Name)?.GetCustomAttributes(true); } else { _customAttributesTemp = context.Request.ServiceInstance.GetType().GetMethod(methodInfo.Name)?.GetCustomAttributes(true); } Cache("CustomAttributes")[customAttributeKey] = _customAttributesTemp; } if (_customAttributesTemp != null) { context.Request.Properties["CustomAttributes"] = (object[])_customAttributesTemp; } //Putting Custom Class Attributes to cache and context object _customClassAttributesTemp = null; string customClassAttributeKey = $"{serviceTypeName}.Attributes"; if (!Cache("CustomClassAttributes").TryGetValue(customClassAttributeKey, out _customClassAttributesTemp)) { _customClassAttributesTemp = context.Request.ServiceInstance.GetType().GetCustomAttributes(); Cache("CustomClassAttributes")[customClassAttributeKey] = _customClassAttributesTemp; } if (_customClassAttributesTemp != null) { context.Request.Properties["CustomClassAttributes"] = (object[])_customClassAttributesTemp; } await _next.Invoke(context); }
public async Task Invoke(InvokeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } object[] customAttributes = (object[])context.Request.Properties["CustomAttributes"]; DatabaseConnection databaseConnection = customAttributes.FirstOrDefault(t => t.GetType() == typeof(DatabaseConnection)) as DatabaseConnection; bool isDatabaseConnectionEnabled = databaseConnection == null ? true : databaseConnection.IsEnabled; if (!isDatabaseConnectionEnabled) { await _next.Invoke(context); } else { var appContext = Application.Current.Context; Transactional transactional = customAttributes.FirstOrDefault(t => t.GetType() == typeof(Transactional)) as Transactional; bool isTransactionEnabled = transactional == null ? false : transactional.IsEnabled; DbConnection connection = GetDbConnection(DbContextOptions.DbProviderName); DatabaseContext ctx = null; if (isTransactionEnabled) { connection.ConnectionString = DbContextOptions.WriteConnectionString; using (ctx = new DatabaseContext(true, connection)) { ctx.DbProviderName = DbContextOptions.DbProviderName; ServiceContext serviceContext = (ServiceContext)context.Request.Properties["ServiceContext"]; serviceContext.AddItem("DatabaseContext", ctx); await _next.Invoke(context); InvokeResult invokeResult = context.Result; if (invokeResult?.Value != null) { dynamic result = invokeResult.Value; if (result.GetType().Name == typeof(ServiceResponse <>).Name) { if (result?.IsSuccess == true) { ctx.Commit(); } else { ctx.Transaction.Rollback(); } } else { ctx.Commit(); } } else { ctx.Transaction.Rollback(); } } } else { connection.ConnectionString = DbContextOptions.ReadConnectionString; using (ctx = new DatabaseContext(false, connection)) { ctx.DbProviderName = DbContextOptions.DbProviderName; ServiceContext serviceContext = (ServiceContext)context.Request.Properties["ServiceContext"]; serviceContext.AddItem("DatabaseContext", ctx); await _next.Invoke(context); } } } }