Ejemplo n.º 1
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;


            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }


            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                var claimsIdentity = await _appSystemAuthentication.Do(context, _generatorName);


                if (claimsIdentity == null)
                {
                    context.User = null;
                }
                else
                {
                    context.User = new ClaimsPrincipal(claimsIdentity);
                }

                await _nextMiddleware(context);
            });
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 从DI容器获取默认目录名称的日志
 /// 提供handler回调处理
 /// 默认目录名称来自DefaultCategoryName属性
 /// </summary>
 /// <param name="handler"></param>
 public static void GetLogger(Action <ILogger> handler)
 {
     using (var diContainer = DIContainerContainer.CreateContainer())
     {
         var logger = diContainer.Get <ILoggerFactory>().CreateLogger(DefaultCategoryName);
         handler(logger);
     }
 }
Ejemplo n.º 3
0
        public async Task Invoke(HttpContext context)
        {
            var logger = _loggerFactory.CreateLogger(_categoryName);
            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                using (var diContainer = DIContainerContainer.CreateContainer())
                {
                    ContextContainer.SetValue <IDIContainer>(_name, diContainer);

                    var replaceExcludePaths = await _appGetOutputStreamReplaceExcludePaths.Do();
                    bool needReplace        = true;
                    if (context.Request.Path.HasValue)
                    {
                        //检查当前请求路径是否匹配
                        foreach (var item in replaceExcludePaths)
                        {
                            Regex regex = new Regex(item, RegexOptions.IgnoreCase);
                            if (regex.IsMatch(context.Request.Path.Value))
                            {
                                needReplace = false;
                                break;
                            }
                        }
                    }

                    if (needReplace)
                    {
                        Stream originalBody = context.Response.Body;
                        try
                        {
                            using (var responseStream = new MemoryStream())
                            {
                                context.Response.Body = responseStream;


                                await InnerInvoke(context);


                                responseStream.Position = 0;
                                await responseStream.CopyToAsync(originalBody);
                            }
                        }
                        finally
                        {
                            context.Response.Body = originalBody;
                        }
                    }
                    else
                    {
                        await InnerInvoke(context);
                    }
                }
            });
        }
Ejemplo n.º 4
0
        protected override async Task OnRealAuthorizationAsync(AuthorizationFilterContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(ErrorCatalogName);
            }

            await HttpErrorHelper.ExecuteByAuthorizationFilterContextAsync(context, logger, async() =>
            {
                //如果_directGeneratorName不为空,则直接使用该生成器名称
                if (!string.IsNullOrEmpty(_directGeneratorName))
                {
                    var authorizeResult = await _appUserAuthorize.Do(null, _directGeneratorName);
                    //存储到http上下文中
                    context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                }

                //判断是否已经通过验证
                if (context.HttpContext.User != null && context.HttpContext.User.Identity != null && context.HttpContext.User.Identity.IsAuthenticated && context.HttpContext.User.Claims != null)
                {
                    var authorizeResult = await _appUserAuthorize.Do(context.HttpContext.User.Claims, _userGeneratorName);

                    //存储到Http上下文中
                    context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                    //authorizeResult.Execute();
                }
                else
                {
                    if (_allowAnonymous)
                    {
                        //未通过验证,但允许匿名,则调用匿名上下文生成
                        var authorizeResult = await _appUserAuthorize.Do(null, _anonymousGeneratorName);
                        //存储到http上下文中
                        context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                        //authorizeResult.Execute();
                    }
                    else
                    {
                        //返回错误响应

                        ErrorMessage errorMessage = new ErrorMessage()
                        {
                            Code    = (int)Errors.AuthorizeFail,
                            Message = string.Format(StringLanguageTranslate.Translate(TextCodes.AuthorizeFail, "用户授权失败,没有找到对应的身份信息"))
                        };
                        context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                    }
                }
            });
        }
Ejemplo n.º 5
0
        protected override async Task OnRealAuthorizationAsync(AuthorizationFilterContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(ErrorCatalogName);
            }

            await HttpErrorHelper.ExecuteByAuthorizationFilterContextAsync(context, logger, async() =>
            {
                //检查在http头中是否已经存在Authorization
                if (!context.HttpContext.Request.Headers.TryGetValue("WhitelistAuthorization", out StringValues authorizationValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundAuthorizationInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundWhitelistAuthorizationInHttpHeader, "在http头中没有找到WhitelistAuthorization")
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }
                //检查在http头中是否已经存在SystemName
                if (!context.HttpContext.Request.Headers.TryGetValue("SystemName", out StringValues systemNameValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundSystemNameInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundSystemNameInHttpHeader, "在http头中没有找到SystemName")
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }

                //获取ActionName的全路径名称
                var actinName = context.ActionDescriptor.DisplayName.Split(' ')[0];
                //获取访问的IP
                var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();

                //执行验证
                var validateResult = await _appValidateRequestForWhitelist.Do(actinName, systemNameValue[0], authorizationValue[0], ip);

                if (!validateResult.Result)
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.WhitelistValidateFail,
                        Message = string.Format(StringLanguageTranslate.Translate(TextCodes.WhitelistValidateFail, "系统操作{0}针对调用方系统{1}的白名单验证未通过,原因:{2}"), actinName, systemNameValue[0], validateResult.Description)
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }
            });
Ejemplo n.º 6
0
        private static ILogger GetLogger(string categoryName)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                if (categoryName == null)
                {
                    logger = loggerFactory.CreateLogger(DefaultCategoryName);
                }
                else
                {
                    logger = loggerFactory.CreateLogger(categoryName);
                }
            }

            return(logger);
        }
Ejemplo n.º 7
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }


            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                var contextInit = await _appInternationalizationExecute.Do(context.Request, _name);

                context.Items["InternationalizationContextInit"] = contextInit;

                await _nextMiddleware(context);
            });
        }
        public async Task <IDTOperationRecordPollingRollbackController> Execute(string storeGroupName, string memberName)
        {
            //获取存储组
            var storeGroup = await _storeGroupRepositoryCacheProxy.QueryByName(storeGroupName);

            if (storeGroup == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFounStoreGroupMemberByName,
                    DefaultFormatting = "找不到名称为{0}的存储组",
                    ReplaceParameters = new List <object>()
                    {
                        storeGroupName
                    }
                };

                throw new UtilityException((int)Errors.NotFounStoreGroupByName, fragment);
            }
            //获取指定的组成员
            var groupMember = await storeGroup.GetMember(memberName);


            if (groupMember == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundStoreGroupMemberInGroup,
                    DefaultFormatting = "在名称为{0}的存储组下找不到名称为{1}的成员",
                    ReplaceParameters = new List <object>()
                    {
                        storeGroupName, memberName
                    }
                };

                throw new UtilityException((int)Errors.NotFoundStoreGroupMemberInGroup, fragment);
            }

            var pollingResult = await PollingHelper.Polling <DTOperationRecord>(
                async() =>
            {
                await Task.CompletedTask;
                return
                (new AsyncInteration <DTOperationRecord>
                 (
                     async(index) =>
                {
                    if (index == 0)
                    {
                        while (true)
                        {
                            var completeList = await _dtOperationRecordRepository.QueryBySkip(groupMember.StoreInfo, (int)DTOperationRecordStatus.Complete, 0, 500);

                            await ParallelHelper.ForEach(completeList, 5,

                                                         async(record) =>
                            {
                                await record.Delete();
                            }
                                                         );


                            if (completeList.Count < 500)
                            {
                                break;
                            }
                        }
                    }

                    var datas = await _dtOperationRecordRepository.QueryBySkip(groupMember.StoreInfo, (int)DTOperationRecordStatus.UnComplete, index * 500, 500);
                    return datas;
                }
                 ));
            }, 5, 500,
                async(record) =>
            {
                try
                {
                    using (var diContainer = DIContainerContainer.CreateContainer())
                    {
                        var orginialDI = ContextContainer.GetValue <IDIContainer>("DI");
                        try
                        {
                            ContextContainer.SetValue <IDIContainer>("DI", diContainer);

                            if (await record.NeedCancel())
                            {
                                await record.Cancel();
                            }
                        }
                        finally
                        {
                            ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exception rootEx = ex;
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    if (ex != rootEx)
                    {
                        await record.UpdateErrorMessage($"root message:{rootEx.Message},inner message:{ex.Message},root Stack:{rootEx.StackTrace},inner Stack:{ex.StackTrace}");
                    }
                    else
                    {
                        await record.UpdateErrorMessage($"message:{rootEx.Message},Stack:{rootEx.StackTrace}");
                    }
                }
            },
                null,
                async(ex) =>
            {
                LoggerHelper.LogError(ErrorLoggerCategoryName, $"DTOperationRecordPollingRollbackService Execute Error,ErrorMessage:{ex.Message},StackTrace:{ex.StackTrace}");
            }
                );

            DTOperationRecordPollingRollbackControllerDefault controller = new DTOperationRecordPollingRollbackControllerDefault(pollingResult);

            return(controller);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 执行所有关联的队列
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public async Task <ISQueueProcessGroupExecuteResult> Execute(SQueueProcessGroup group)
        {
            bool errorLogRecord = false;
            //声明一个轮询配置列表,队列的执行通过轮询处理帮助器管理,保证只有一个主控线程被占用
            List <PollingConfiguration> pollingConfigurations = new List <PollingConfiguration>();

            await GetAllQueue(group, async (queue) =>
            {
                pollingConfigurations.Add(new PollingConfiguration()
                {
                    Action = async() =>
                    {
                        try
                        {
                            if (AdministratorClaimGeneratorName != null && AdministratorClaimContextGeneratorName != null)
                            {
                                //生成上下文
                                var administratorClaimGenerator = await _environmentClaimGeneratorRepository.QueryByName(AdministratorClaimGeneratorName);
                                if (administratorClaimGenerator == null)
                                {
                                    var fragment = new TextFragment()
                                    {
                                        Code = TextCodes.NotFoundEnvironmentClaimGeneratorByName,
                                        DefaultFormatting = "没有找到名称为{0}的环境声明生成器",
                                        ReplaceParameters = new List <object>()
                                        {
                                            AdministratorClaimGeneratorName
                                        }
                                    };

                                    throw new UtilityException((int)Errors.NotFoundEnvironmentClaimGeneratorByName, fragment);
                                }

                                var claims = await administratorClaimGenerator.Generate();

                                var administratorClaimContextGenerator = await _claimContextGeneratorRepository.QueryByName(AdministratorClaimContextGeneratorName);
                                if (administratorClaimContextGenerator == null)
                                {
                                    var fragment = new TextFragment()
                                    {
                                        Code = TextCodes.NotFoundClaimContextGeneratorByName,
                                        DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                                        ReplaceParameters = new List <object>()
                                        {
                                            AdministratorClaimContextGeneratorName
                                        }
                                    };

                                    throw new UtilityException((int)Errors.NotFoundClaimContextGeneratorByName, fragment);
                                }

                                administratorClaimContextGenerator.ContextInit(claims.Claims);
                            }

                            ConcurrentDictionary <Guid, Guid> errorMessageList = new ConcurrentDictionary <Guid, Guid>();

                            //获取队列中的消息
                            await _smessageRepository.QueryAllByQueue(queue, 500, async(messages) =>
                            {
                                bool needRestart = false;


                                foreach (var message in messages)
                                {
                                    StatusResult executeResult = new StatusResult()
                                    {
                                        Status = 2
                                    };

                                    try
                                    {
                                        using (var diContainer = DIContainerContainer.CreateContainer())
                                        {
                                            var orginialDI = ContextContainer.GetValue <IDIContainer>("DI");
                                            try
                                            {
                                                ContextContainer.SetValue <IDIContainer>("DI", diContainer);
                                                //对每个消息执行处理
                                                executeResult = await message.Execute();
                                            }
                                            finally
                                            {
                                                ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        while (ex.InnerException != null)
                                        {
                                            ex = ex.InnerException;
                                        }
                                        //if (errorMessageList.Count<=100000)
                                        //{
                                        //if (!errorMessageList.ContainsKey(message.ID))
                                        //{
                                        //   errorMessageList.TryAdd(message.ID, message.ID);
                                        LoggerHelper.LogError(ErrorLoggerCategoryName,
                                                              $"SQueueProcessGroup {group.Name} Execute Error,message Type {message.Type},message id {message.ID.ToString()},ErrorMessage:{await ex.GetCurrentLcidMessage()},StackTrace:{ex.StackTrace}");
                                        //}
                                        //}
                                    }

                                    if (executeResult.Status == 0)
                                    {
                                        //执行成功
                                        needRestart = true;
                                        await message.Delete();

                                        //errorMessageList.TryRemove(message.ID, out Guid deleteId);
                                    }
                                    else
                                    {
                                        if (executeResult.Status == 3)
                                        {
                                            needRestart = true;
                                            //执行失败
                                            //LoggerHelper.LogError(ErrorLoggerCategoryName, $"SQueueProcessGroup Message Execute Error,Type:{message.Type},Key:{message.Key},Data:{message.Data},ErrorMessage:{executeResult.Description}");
                                        }
                                    }
                                }

                                if (needRestart)
                                {
                                    return(await Task.FromResult(false));
                                }
                                else
                                {
                                    return(await Task.FromResult(true));
                                }
                            });

                            //System.Threading.Thread.Sleep(1000);
                        }
                        catch (Exception ex)
                        {
                            //if (!errorLogRecord)
                            //{
                            while (ex.InnerException != null)
                            {
                                ex = ex.InnerException;
                            }
                            LoggerHelper.LogError(ErrorLoggerCategoryName,
                                                  $"SQueueProcessGroup {group.Name} Execute Error,ErrorMessage:{await ex.GetCurrentLcidMessage()},StackTrace:{ex.StackTrace}");
                            //    errorLogRecord = true;
                            //}

                            await Task.Delay(1000 * 60 * 2);
                        }
                    },
                    Interval = queue.Interval
                }
                                          );

                await Task.FromResult(0);
            });

            var pollingResult = PollingHelper.Polling(pollingConfigurations,
                                                      async(ex) =>
            {
                LoggerHelper.LogError(ErrorLoggerCategoryName,
                                      $"PollingHelper Execute Error,ErrorMessage:{ex.Message},StackTrace:{ex.StackTrace}");
            }
                                                      );

            return(new SQueueProcessGroupExecuteResultDefalut(pollingResult));
        }
Ejemplo n.º 10
0
            public async Task Execute(IJobExecutionContext context)
            {
                //获取调度动作名称
                var actionName = context.JobDetail.JobDataMap.GetString("ActionName");
                //获取调度动作名称
                var groupName = context.JobDetail.JobDataMap.GetString("GroupName");
                //获取初始化类型
                var initType = context.JobDetail.JobDataMap.GetString("InitType");
                //获取初始化配置
                var initConfiguration = context.JobDetail.JobDataMap.GetString("InitConfiguration");


                try
                {
                    if (!_actionRunStatuses.TryGetValue(actionName, out ScheduleActionRunStatus runStatus))
                    {
                        var scheduleAction = await _scheduleActionRepository.QueryByName(actionName);

                        if (scheduleAction == null)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.NotFoundScheduleActionByName,
                                DefaultFormatting = "找不到名称为{0}的调度动作",
                                ReplaceParameters = new List <object>()
                                {
                                    actionName
                                }
                            };

                            throw new UtilityException((int)Errors.NotFoundScheduleActionByName, fragment);
                        }
                        runStatus = new ScheduleActionRunStatus()
                        {
                            Action = scheduleAction, Status = 0
                        };
                        _actionRunStatuses.Add(actionName, runStatus);
                    }


                    if (runStatus.Status == 0)
                    {
                        /* var environmentClaimGenerator = await _environmentClaimGeneratorRepository.QueryByName(_environmentClaimGeneratorName);
                         * var claimContextGenerator = await _claimContextGeneratorRepository.QueryByName(_claimContextGeneratorName);
                         *
                         *
                         *
                         * if (environmentClaimGenerator == null)
                         * {
                         *   var fragment = new TextFragment()
                         *   {
                         *       Code = TextCodes.NotFoundEnvironmentClaimGeneratorByName,
                         *       DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                         *       ReplaceParameters = new List<object>() { _environmentClaimGeneratorName }
                         *   };
                         *
                         *   throw new UtilityException((int)Errors.NotFoundEnvironmentClaimGeneratorByName, fragment);
                         * }
                         *
                         * if (claimContextGenerator == null)
                         * {
                         *   var fragment = new TextFragment()
                         *   {
                         *       Code = TextCodes.NotFoundClaimContextGeneratorByName,
                         *       DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                         *       ReplaceParameters = new List<object>() { _claimContextGeneratorName }
                         *   };
                         *
                         *   throw new UtilityException((int)Errors.NotFoundClaimContextGeneratorByName, fragment);
                         * }
                         *
                         * var claims = await environmentClaimGenerator.Generate();
                         * claimContextGenerator.ContextInit(claims.Claims);
                         */
                        using (var diContainer = DIContainerContainer.CreateContainer())
                        {
                            var orginialDI = ContextContainer.GetValue <IDIContainer>("DI");
                            try
                            {
                                ContextContainer.SetValue <IDIContainer>("DI", diContainer);

                                var initGeneratorService = getInitGeneratorService(initType);
                                var initService          = await initGeneratorService.Generator(initConfiguration);

                                initService.Init();

                                if (_useLog)
                                {
                                    LoggerHelper.LogInformation(_informationCategory, $"ScheduleAction {actionName} in Grioup {groupName} start");
                                }
                                var actionResult = await runStatus.Action.Execute();

                                runStatus.Result = actionResult;

                                if (runStatus.Result.Polling)
                                {
                                    runStatus.Status = 1;
                                }
                                else
                                {
                                    await runStatus.Result.Stop();

                                    if (_useLog)
                                    {
                                        LoggerHelper.LogInformation(_informationCategory, $"ScheduleAction {actionName} in Grioup {groupName} stop");
                                    }
                                }
                            }
                            finally
                            {
                                ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.LogError(_errorCategory, $"ScheduleAction {actionName} in Grioup {groupName} start error,detail:{ex.Message},stacktrace:{ex.StackTrace}");
                    //throw;
                }
            }
Ejemplo n.º 11
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }

            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                bool complete = false;
                //检查在http头中是否已经存在WhitelistAuthorization
                if (!context.Request.Headers.TryGetValue("WhitelistAuthorization", out StringValues authorizationValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundAuthorizationInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundWhitelistAuthorizationInHttpHeader, "在http头中没有找到WhitelistAuthorization")
                    };

                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }
                //检查在http头中是否已经存在SystemName
                if (!context.Request.Headers.TryGetValue("SystemName", out StringValues systemNameValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundSystemNameInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundSystemNameInHttpHeader, "在http头中没有找到SystemName")
                    };
                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }

                //获取请求路径名称
                var actinName = context.Request.Path;
                //获取访问的IP
                var ip = context.Connection.RemoteIpAddress.ToString();

                //执行验证
                var validateResult = await _appValidateRequestForWhitelist.Do(actinName, systemNameValue[0], authorizationValue[0], ip);

                if (!validateResult.Result)
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.WhitelistValidateFail,
                        Message = string.Format(StringLanguageTranslate.Translate(TextCodes.WhitelistValidateFail, "系统操作{0}针对调用方系统{1}的白名单验证未通过,原因:{2}"), actinName, systemNameValue[0], validateResult.Description)
                    };
                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }

                //如果检测通过,则继续执行下面的管道
                if (!complete)
                {
                    await _nextMiddleware(context);
                }
            });