public EntityBase() { var impFactory = GetIMPFactory(); if (impFactory == null) { if (_impGenerateServiceFactory != null) { _imp = _impGenerateServiceFactory.Create().Generate <T>(); } else { var di = ContextContainer.GetValue <IDIContainer>("DI"); if (di == null) { _imp = DIContainerContainer.Get <T>(); } else { _imp = di.Get <T>(); } } } else { _imp = impFactory.Create(); } }
/// <summary> /// 初始化日志 /// </summary> /// <param name="builder"></param> public static void InitLogger(ILoggingBuilder builder) { var mainHandler = DIContainerContainer.Get <ILoggingBuilderHandler>(); var loggerConfiguration = ConfigurationContainer.Get <LoggerConfiguration>(ConfigurationNames.Logger); mainHandler.Execute(builder, loggerConfiguration).Wait(); }
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); }); }
/// <summary> /// 初始化Crm服务 /// </summary> /// <returns></returns> public static CrmService CreateCrmService() { var coreConfiguration = ConfigurationContainer.Get <UserCenterAssConfiguration>(ConfigurationNames.Application); var crmService = DIContainerContainer.Get <CrmService>(); if (coreConfiguration.DyCRMSetting != null) { var dyCRMSetting = coreConfiguration.DyCRMSetting; if (crmService != null) { crmService.CrmApiMaxRetry = dyCRMSetting.CrmApiMaxRetry; crmService.CrmApiVersion = dyCRMSetting.CrmApiVersion; crmService.CrmUrl = dyCRMSetting.CrmUrl; crmService.TokenServiceType = dyCRMSetting.TokenServiceType; crmService.TokenServiceParameters.Add("Domain", dyCRMSetting.Domain); crmService.TokenServiceParameters.Add("AdfsUrl", dyCRMSetting.AdfsUrl); crmService.TokenServiceParameters.Add("CrmUrl", dyCRMSetting.CrmUrl); crmService.TokenServiceParameters.Add("ClientId", dyCRMSetting.ClientId); crmService.TokenServiceParameters.Add("ClientSecret", dyCRMSetting.ClientSecret); crmService.TokenServiceParameters.Add("UserName", dyCRMSetting.UserName); crmService.TokenServiceParameters.Add("Password", dyCRMSetting.Password); crmService.TokenServiceParameters.Add("RedirectUri", dyCRMSetting.RedirectUri); ContextContainer.SetValue <Guid>(ContextExtensionTypes.MemberInstanceId, dyCRMSetting.MemberInstanceId); } } return(crmService); }
/// <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); } }
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); } } }); }
public void RegisterHandlerDescription(string requestType, IList <ISRRFilter> filters, IFactory <ISRRRequestHandler> handlerFactory) { var handlerDescription = DIContainerContainer.Get <SRRRequestHandlerDescriptionDefault>(); foreach (var item in filters) { handlerDescription.Filters.Add(item); } handlerDescription.HandlerFactory = handlerFactory; _handlerDescriptions[requestType] = handlerDescription; }
public ISRRHostContainer Register(string name, Action <ISRRHostConfiguration> configure) { var configuration = DIContainerContainer.Get <SRRHostConfigurationDefault>(); configure(configuration); var hostService = DIContainerContainer.Get <ISRRHostService>(); hostService.Configure(configuration); _services[name] = hostService; return(this); }
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); } } }); }
public async Task <AuthorizationPolicy> GetPolicyAsync(string policyName) { if (policyName.StartsWith(_prefix, StringComparison.OrdinalIgnoreCase)) { var httpContext = _httpContextAccessor.HttpContext; var service = (IHttpContextPolicyResolveService)DIContainerContainer.Get(Type.GetType(policyName.Substring(_prefix.Length))); return(await service.Execute(httpContext)); } else { return(await _defaultProvider.GetPolicyAsync(policyName)); } }
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); } });
public async Task Start() { //检查grpc服务过滤器查找服务是否已经有值,如果没有,使用工厂创建 if (_grpcServiceFindFilterService == null) { _grpcServiceFindFilterService = _grpcServiceFindFilterServiceFactory.Create(); } //检查grpc服务查找服务是否已经有值,如果没有,使用工厂创建 if (_grpcServiceFindService == null) { _grpcServiceFindService = _grpcServiceFindServiceFactory.Create(); } //获取Grpc服务信息 var grpcServiceInfos = await _grpcServiceFindService.Execute(); List <GrpcServiceDescription> grpcServiceDescriptionList = new List <GrpcServiceDescription>(); GrpcServiceDescription newGrpcServiceDescription; //组装Grpc服务描述,为GrpcHostConfiguartion赋值 //以及为Gprc服务的服务定义赋值 foreach (var infoItem in grpcServiceInfos) { newGrpcServiceDescription = new GrpcServiceDescription() { NamespaceType = infoItem.NameSpaceType, ServiceType = infoItem.ServiceType }; grpcServiceDescriptionList.Add(newGrpcServiceDescription); //获取每个Grpc服务的过滤器 var serviceFilters = await _grpcServiceFindFilterService.Execute(newGrpcServiceDescription.ServiceType); newGrpcServiceDescription.Filters = serviceFilters; //获取合并后的链式拦截器 var chainInterceptor = await getChainInterceptor(_configuration.GlobalFilters, serviceFilters); //组装Grpc服务器中的服务定义 var gprcService = DIContainerContainer.Get(newGrpcServiceDescription.ServiceType); ServerServiceDefinition newServerServiceDefinition = ((ServerServiceDefinition)newGrpcServiceDescription.NamespaceType.GetMethod("BindService").Invoke(null, new object[] { gprcService })).Intercept(chainInterceptor); _grpcServer.Services.Add(newServerServiceDefinition); } //为Gprc服务的端口定义赋值 foreach (var portItem in _configuration.Ports) { _grpcServer.Ports.Add(new ServerPort(portItem.Host, portItem.Port, portItem.Credential)); } _grpcServer.Start(); }
//执行之前处理 public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { #region 通过请求token获取当前用户登录信息 var coreConfiguration = ConfigurationContainer.Get <BaseConfiguration>(ConfigurationNames.Application); if (coreConfiguration.DyCRMSetting != null) { var dyCRMSetting = coreConfiguration.DyCRMSetting; _baseUrl = $"{dyCRMSetting.CrmUrl}/api/data/v{dyCRMSetting.CrmApiVersion}"; } IHttpContextAccessor _accessor = new HttpContextAccessor(); var token = _accessor.HttpContext.Request.Headers["token"].ToString(); if (!string.IsNullOrEmpty(token)) { var helper = DIContainerContainer.Get <AdfsEndpointRepositoryHelper>(); string userName = ""; if (token.Contains("ADAUTH:")) { userName = token.Split(':')[1]; if (userName.Contains("\\")) { userName = userName.Split("\\")[1]; } } else { var endpoint = await helper.QueryByName("Main"); var claims = await endpoint.ValidateJWT(token, new string[] { _baseUrl }); userName = claims.FindFirst(System.Security.Claims.ClaimTypes.Name).Value; } if (!string.IsNullOrEmpty(userName)) { #region 缓存用户登录信息 var logioninfo = await helper.GetLoginInfo(userName, token); if (logioninfo != null) { ContextContainer.SetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo, logioninfo); } #endregion } } else { //throw new Exception("接口鉴权失败"); } #endregion await next(); }
/// <summary> /// 初始化静态化信息 /// 所有通过静态属性来配置的信息,都在该方法中初始化 /// </summary> public static void InitStaticInfo() { InitCrmStaticInfo(); //为HttpClinetHelper的HttpClientFactory赋值 HttpClinetHelper.HttpClientFactoryGenerator = () => DIContainerContainer.Get <IHttpClientFactory>(); //为AdfsHelper.HttpClientFactory赋值 AdfsHelper.HttpClientFactoryGenerator = () => DIContainerContainer.Get <IHttpClientFactory>(); //CrmServiceFactoryRepositoryHelper.Repository = DIContainerContainer.Get<ICrmServiceFactoryRepository>(); //为日志构建器处理的提供方处理工厂赋值 LoggingBuilderHandlerDefault.ProviderHandlerFactories[LoggerProviderHandlerNames.ApplicationInsights] = DIContainerContainer.Get <LoggingBuilderProviderHandlerForApplicationInsightsFactory>(); LoggingBuilderHandlerDefault.ProviderHandlerFactories[LoggerProviderHandlerNames.Console] = DIContainerContainer.Get <LoggingBuilderProviderHandlerForConsoleFactory>(); LoggingBuilderHandlerDefault.ProviderHandlerFactories[LoggerProviderHandlerNames.CommonLog] = DIContainerContainer.Get <LoggingBuilderProviderHandlerForCommonLogFactory>(); LoggingBuilderHandlerDefault.ProviderHandlerFactories[LoggerProviderHandlerNames.CommonLogLocal] = DIContainerContainer.Get <LoggingBuilderProviderHandlerForCommonLogLocalFactory>(); //为HttpClaimGeneratorIMP.HttpClaimGeneratorServiceFactories增加键值对 HttpClaimGeneratorIMP.HttpClaimGeneratorServiceFactories[HttpClaimGeneratorServiceTypes.Inner] = DIContainerContainer.Get <HttpClaimGeneratorServiceForInnerFactory>(); //为ClaimContextGeneratorIMP.ClaimContextGeneratorServiceFactories增加键值对 ClaimContextGeneratorIMP.ClaimContextGeneratorServiceFactories[ClaimContextGeneratorServiceTypes.Inner] = DIContainerContainer.Get <ClaimContextGeneratorServiceForInnerFactory>(); ClaimContextGeneratorIMP.ClaimContextGeneratorServiceFactories[ClaimContextGeneratorServiceTypes.Default] = DIContainerContainer.Get <ClaimContextGeneratorServiceForDefaultFactory>(); //为JwtGenerateCreateSignKeyMainService.JwtGenerateValidateSignKeyMainService赋值 JwtGenerateCreateSignKeyMainService.JwtGenerateCreateSignKeyServiceFactories[JwtGenerateCreateSignKeyServiceTypes.RsaPrivate] = DIContainerContainer.Get <JwtGenerateCreateSignKeyServiceForRsaPrivateFactory>(); //为JwtGenerateValidateSignKeyMainService.JwtGenerateValidateSignKeyServiceFactories赋值 JwtGenerateValidateSignKeyMainService.JwtGenerateValidateSignKeyServiceFactories[JwtGenerateValidateSignKeyServiceTypes.MetadataService] = DIContainerContainer.Get <JwtGenerateValidateSignKeyServiceForMetadataServiceFactory>(); JwtGenerateValidateSignKeyMainService.JwtGenerateValidateSignKeyServiceFactories[JwtGenerateValidateSignKeyServiceTypes.RsaPublic] = DIContainerContainer.Get <JwtGenerateValidateSignKeyServiceForRsaPublicFactory>(); //为JwtValidateParameterBuildMainService.JwtValidateParameterBuildServiceFactories赋值 JwtValidateParameterBuildMainService.JwtValidateParameterBuildServiceFactories[JwtValidateParameterBuildServiceTypes.Audience] = DIContainerContainer.Get <JwtValidateParameterBuildServiceForAudienceFactory>(); JwtValidateParameterBuildMainService.JwtValidateParameterBuildServiceFactories[JwtValidateParameterBuildServiceTypes.Issuer] = DIContainerContainer.Get <JwtValidateParameterBuildServiceForIssuerFactory>(); JwtValidateParameterBuildMainService.JwtValidateParameterBuildServiceFactories[JwtValidateParameterBuildServiceTypes.Lifetime] = DIContainerContainer.Get <JwtValidateParameterBuildServiceForLifetimeFactory>(); CommonQueueConsumeEndpointIMP.QueueRealExecuteServiceFactories[CommonQueueTypes.AzureServiceBus] = DIContainerContainer.Get <QueueRealExecuteServiceForAzureServiceBusFactory>(); CommonQueueProductEndpointIMP.QueueRealExecuteServiceFactories[CommonQueueTypes.AzureServiceBus] = DIContainerContainer.Get <QueueRealExecuteServiceForAzureServiceBusFactory>(); QueueRealExecuteServiceForAzureServiceBus.ConsumeErrorLoggerCategoryName = "AzureServiceBus"; QueueRealExecuteServiceForAzureServiceBus.ConvertFromServiceFactories[AzureServiceBusMessageConvertFromServiceNames.Default] = DIContainerContainer.Get <AzureServiceBusMessageConvertFromForDefaultFactory>(); QueueRealExecuteServiceForAzureServiceBus.ConvertToServiceFactories[AzureServiceBusMessageConvertToServiceNames.Default] = DIContainerContainer.Get <AzureServiceBusMessageConvertToForDefaultFactory>(); TokenControllerIMP.TokenControllerServiceFactories[TokenControllerTypes.JWT] = DIContainerContainer.Get <TokenControllerServiceForJWTFactory>(); InitThirdInterfaceSetting(); }
private IHashGroupStrategyService GetStrategyService(HashGroup group) { if (_strategyServiceFactory == null || group.Strategy.StrategyServiceFactoryType != _strategyServiceFactoryTypeName) { lock (_lockObj) { if (_strategyServiceFactory == null || group.Strategy.StrategyServiceFactoryType != _strategyServiceFactoryTypeName) { _strategyServiceFactoryTypeName = group.Strategy.StrategyServiceFactoryType; Type strategyServiceFactoryType = Type.GetType(group.Strategy.StrategyServiceFactoryType); object strategyServiceFactory; if (group.Strategy.StrategyServiceFactoryTypeUseDI == true) { //通过DI容器创建 strategyServiceFactory = DIContainerContainer.Get(strategyServiceFactoryType); } else { //通过反射创建 strategyServiceFactory = strategyServiceFactoryType.Assembly.CreateInstance(strategyServiceFactoryType.FullName); } if (!(strategyServiceFactory is IFactory <IHashGroupStrategyService>)) { var fragment = new TextFragment() { Code = TextCodes.HashGroupStrategyServiceFactoryTypeError, DefaultFormatting = "在一致性哈希策略{0}中,策略服务类型{1}未实现接口IFactory<IHashGroupStrategyService>", ReplaceParameters = new List <object>() { group.Strategy.Name, group.Strategy.StrategyServiceFactoryType } }; throw new UtilityException((int)Errors.HashGroupStrategyServiceFactoryTypeError, fragment); } _strategyServiceFactory = (IFactory <IHashGroupStrategyService>)strategyServiceFactory; } } } return(_strategyServiceFactory.Create()); }
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); }
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 <ICrmService> Create(string configuration) { if (TextReplaceService != null) { configuration = await TextReplaceService.Replace(configuration); } var crmService = DIContainerContainer.Get <CrmService>(); var serviceConfiguration = JsonSerializerHelper.Deserialize <CrmServiceConfiguration>(configuration); foreach (var item in serviceConfiguration.TokenServiceParameters) { crmService.TokenServiceParameters.Add(item.Key, item.Value); } crmService.CrmApiVersion = serviceConfiguration.CrmApiVersion; crmService.CrmApiMaxRetry = serviceConfiguration.CrmApiMaxRetry; crmService.CrmUrl = serviceConfiguration.CrmUrl; crmService.TokenServiceType = serviceConfiguration.TokenServiceType; return(await Task.FromResult(crmService)); }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseIISIntegration() .ConfigureServices((context, services) => { //初始化配置容器 StartupHelper.InitConfigurationContainer(context.HostingEnvironment.EnvironmentName, _baseUrl); //获取核心配置 var coreConfiguration = ConfigurationContainer.Get <CoreConfiguration>(ConfigurationNames.Application); //初始化DI容器 MainStartupHelper.InitDI(services, coreConfiguration.DISetting); //初始化静态设置 MainStartupHelper.InitStaticInfo(); StartupHelper.InitStaticInfo(); //配置日志工厂 var loggerFactory = LoggerFactory.Create((builder) => { MainStartupHelper.InitLogger(builder); }); DIContainerContainer.Inject <ILoggerFactory>(loggerFactory); }) .ConfigureLogging((builder) => { //初始化日志配置 //MainStartupHelper.InitLogger(builder); }) .ConfigureKestrel(opts => { }) .UseConfiguration(ConfigurationContainer.GetConfiguration(ConfigurationNames.Host)) .UseStartup <Startup>();
/// <summary> /// 初始化DI容器 /// 自动装载被标识的对象 /// </summary> /// <param name="serviceCollection"></param> /// <param name="dISetting"></param> public static void InitDI(IServiceCollection services, ContainerBuilder containerBuilder, DISetting dISetting) { //services.AddHttpClient(); //var serviceProvider = services.BuildServiceProvider(); //containerBuilder.RegisterInstance(serviceProvider.GetService<IHttpClientFactory>()).As<IHttpClientFactory>(); DIContainerForAutofac diContainer = new DIContainerForAutofac(containerBuilder); DIContainerContainer.DIContainer = diContainer; DIContainerInit.Init = new DIContainerInitDefault(); DIContainerInit.Execute(dISetting.SearchAssemblyNames); containerBuilder.RegisterBuildCallback((container) => { diContainer.CompleteInit(container.BeginLifetimeScope()); //初始化静态设置 MainStartupHelper.InitStaticInfo(); InitStaticInfo(); //配置日志工厂 var loggerFactory = LoggerFactory.Create((builder) => { MainStartupHelper.InitLogger(builder); }); DIContainerContainer.Inject <ILoggerFactory>(loggerFactory); }); //装载需要手动处理的DI数据 //Microsoft.AspNetCore.DataProtection.Repositories.IXmlRepository //DIContainerContainer.Inject<IXmlRepository, DataProtectionXmlRepository>(@"Configurations\Dataprotection\key.xml"); }
public ActionResult <IEnumerable <string> > Get() { var service = DIContainerContainer.Get <CrmService>(); return(new string[] { "value1", "value2" }); }
/// <summary> /// 初始化Crm静态信息 /// </summary> public static void InitCrmStaticInfo() { //为CrmMessageHandleSelector.HandleFactories赋值,键为Message类型的全名 CrmMessageHandleSelector.HandleFactories[typeof(CrmAssociateCollectionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForAssociateCollectionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmAssociateCollectionMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForAssociateCollectionMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmAssociateLookupRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForAssociateLookupFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmBatchRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForBatchFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmBoundActionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForBoundActionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmBoundFunctionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForBoundFunctionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmCreateRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForCreateFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmCreateRetrieveRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForCreateRetrieveFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmDeleteRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForDeleteFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmDisAssociateCollectionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForDisAssociateCollectionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmDisAssociateLookupRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForDisAssociateLookupFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveAggregationRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveAggregationFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveCollectionAttributeRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveCollectionAttributeFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveCollectionAttributeAggregationRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveCollectionAttributeAggregationFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveCollectionAttributeReferenceRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveCollectionAttributeReferenceFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveCollectionAttributeSavedQueryRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveCollectionAttributeSavedQueryFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveCollectionAttributeUserQueryRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveCollectionAttributeUserQueryFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityAttributeMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityAttributeMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityAttributeMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityAttributeMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityN2NRelationMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityN2NRelationMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveEntityO2NRelationMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveEntityO2NRelationMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveGlobalOptionSetMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveGlobalOptionSetMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveLookupAttributeRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveLookupAttributeFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveLookupAttributeReferenceRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveLookupAttributeReferenceFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveMultipleFetchRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveMultipleFetchFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveMultiplePageRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveMultiplePageFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveMultipleSavedQueryRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveMultipleSavedQueryFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveMultipleUserQueryRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveMultipleUserQueryFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveN2NRelationMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveN2NRelationMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveN2NRelationMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveN2NRelationMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveO2NRelationMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveO2NRelationMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveO2NRelationMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveO2NRelationMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveRelationMetadataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveRelationMetadataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveRelationMetadataMultipleRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveRelationMetadataMultipleFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmRetrieveSignleAttributeRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForRetrieveSignleAttributeFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUnBoundActionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUnBoundActionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUnBoundFunctionRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUnBoundFunctionFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUpdateRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUpdateFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUpdateRetrieveRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUpdateRetrieveFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUpsertRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUpsertFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmUpsertRetrieveRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForUpsertRetrieveFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmGetFileAttributeUploadInfoRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForGetFileAttributeUploadInfoFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmFileAttributeDeleteDataRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForFileAttributeDeleteDataFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmFileAttributeDownloadChunkingRequestMessage).FullName] = DIContainerContainer.Get <CrmMessageHandleForFileAttributeDownloadChunkingFactory>(); CrmMessageHandleSelector.HandleFactories[typeof(CrmMessageHandleForFileAttributeUploadChunkingFactory).FullName] = DIContainerContainer.Get <CrmMessageHandleForFileAttributeUploadChunkingFactory>(); //为CrmAttributeMetadataHandleSelector.HandleFactories赋值 CrmAttributeMetadataHandleSelector.HandleFactories[CrmAttributeReturnTypes.OptionSet] = DIContainerContainer.Get <CrmAttributeMetadataHandleForOptionSetFactory>(); CrmAttributeMetadataHandleSelector.HandleFactories[CrmAttributeReturnTypes.PickList] = DIContainerContainer.Get <CrmAttributeMetadataHandleForPickListFactory>(); //为CrmServiceTokenGenerateServiceSelector.ServiceFactories赋值 CrmServiceTokenGenerateServiceSelector.ServiceFactories[CrmServiceTokenGenerateServiceTypes.AD] = DIContainerContainer.Get <CrmServiceTokenGenerateServiceForADFactory>(); CrmServiceTokenGenerateServiceSelector.ServiceFactories[CrmServiceTokenGenerateServiceTypes.ADFS] = DIContainerContainer.Get <CrmServiceTokenGenerateServiceForADFSFactory>(); CrmServiceTokenGenerateServiceSelector.ServiceFactories[CrmServiceTokenGenerateServiceTypes.ADFSPassword] = DIContainerContainer.Get <CrmServiceTokenGenerateServiceForADFSPasswordFactory>(); CrmServiceTokenGenerateServiceSelector.ServiceFactories[CrmServiceTokenGenerateServiceTypes.S2S] = DIContainerContainer.Get <CrmServiceTokenGenerateServiceForS2SFactory>(); //为 CrmServiceFactoryIMP.ServiceFactories赋值 CrmServiceFactoryIMP.ServiceFactories[CrmServiceFactoryServiceTypes.Common] = DIContainerContainer.Get <CrmServiceFactoryServiceForCommonFactory>(); //为 CrmRetrieveJTokenConvertService.HandleFactories赋值 CrmRetrieveJTokenConvertService.HandleFactories[typeof(CrmEntity)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityFactory>(); CrmRetrieveJTokenConvertService.HandleFactories[typeof(CrmEntityCollection)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityCollectionFactory>(); CrmRetrieveJTokenConvertService.HandleFactories[typeof(List <CrmEntity>)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityListFactory>(); CrmRetrieveJTokenConvertService.HandleFactories[typeof(CrmEntityReference)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityReferenceCollectionFactory>(); CrmRetrieveJTokenConvertService.HandleFactories[typeof(CrmEntityReferenceCollection)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityReferenceCollectionFactory>(); CrmRetrieveJTokenConvertService.HandleFactories[typeof(List <CrmEntityReference>)] = DIContainerContainer.Get <CrmRetrieveJTokenHandleForCrmEntityReferenceListFactory>(); //为CrmFunctionParameterMainHandle.HandleFactories赋值 CrmFunctionParameterMainHandle.HandleFactories[typeof(bool)] = DIContainerContainer.Get <CrmFunctionParameterHandleForBoolFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(CrmEntityReference)] = DIContainerContainer.Get <CrmFunctionParameterHandleForCrmEntityReferenceFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(CrmEntityReferenceNull)] = DIContainerContainer.Get <CrmFunctionParameterHandleForCrmEntityReferenceNullFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(DateTime)] = DIContainerContainer.Get <CrmFunctionParameterHandleForDateTimeFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(CrmFunctionEnumTypeParameter)] = DIContainerContainer.Get <CrmFunctionParameterHandleForEnumTypeFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(int)] = DIContainerContainer.Get <CrmFunctionParameterHandleForNumberFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(long)] = DIContainerContainer.Get <CrmFunctionParameterHandleForNumberFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(decimal)] = DIContainerContainer.Get <CrmFunctionParameterHandleForNumberFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(float)] = DIContainerContainer.Get <CrmFunctionParameterHandleForNumberFactory>(); CrmFunctionParameterMainHandle.HandleFactories[typeof(string)] = DIContainerContainer.Get <CrmFunctionParameterHandleForStringFactory>(); //为CrmExecuteEntityTypemMainHandle.ServiceFactories赋值 CrmExecuteEntityTypemMainHandle.ServiceFactories[typeof(CrmEntityReference)] = DIContainerContainer.Get <CrmExecuteEntityTypeHandleForCrmEntityReferenceFactory>(); CrmExecuteEntityTypemMainHandle.ServiceFactories[typeof(IList <CrmEntityReference>)] = DIContainerContainer.Get <CrmExecuteEntityTypeHandleForCrmEntityReferenceListFactory>(); CrmExecuteEntityTypemMainHandle.ServiceFactories[typeof(IList <CrmEntityReferenceNull>)] = DIContainerContainer.Get <CrmExecuteEntityTypeHandleForCrmEntityReferenceNullFactory>(); CrmExecuteEntityTypemMainHandle.ServiceFactories[typeof(CrmExecuteEntity)] = DIContainerContainer.Get <CrmExecuteEntityTypeHandleForCrmExecuteEntityFactory>(); CrmExecuteEntityTypemMainHandle.ServiceFactories[typeof(IList <CrmExecuteEntity>)] = DIContainerContainer.Get <CrmExecuteEntityTypeHandleForCrmExecuteEntityListFactory>(); //为CrmAlternateKeyTypeMainHandle.ServiceFactories赋值 CrmAlternateKeyTypeMainHandle.ServiceFactories[typeof(CrmEntityReference)] = DIContainerContainer.Get <CrmAlternateKeyTypeHandleForCrmEntityReferenceFactory>(); CrmAlternateKeyTypeMainHandle.ServiceFactories[typeof(int)] = DIContainerContainer.Get <CrmAlternateKeyTypeHandleForNumberFactory>(); CrmAlternateKeyTypeMainHandle.ServiceFactories[typeof(float)] = DIContainerContainer.Get <CrmAlternateKeyTypeHandleForNumberFactory>(); CrmAlternateKeyTypeMainHandle.ServiceFactories[typeof(decimal)] = DIContainerContainer.Get <CrmAlternateKeyTypeHandleForNumberFactory>(); CrmAlternateKeyTypeMainHandle.ServiceFactories[typeof(string)] = DIContainerContainer.Get <CrmAlternateKeyTypeHandleForStringFactory>(); //为 CrmActionParameterMainHandle.HandleFactories赋值 CrmActionParameterMainHandle.HandleFactories[typeof(CrmEntityReference)] = DIContainerContainer.Get <CrmActionParameterHandleForCrmEntityReferenceFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(IList <CrmEntityReference>)] = DIContainerContainer.Get <CrmActionParameterHandleForCrmEntityReferenceListFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(CrmEntityReferenceNull)] = DIContainerContainer.Get <CrmActionParameterHandleForCrmEntityReferenceNullFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(CrmExecuteEntity)] = DIContainerContainer.Get <CrmActionParameterHandleForCrmExecuteEntityFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(IList <CrmExecuteEntity>)] = DIContainerContainer.Get <CrmActionParameterHandleForCrmExecuteEntityListFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(int)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(long)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(decimal)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(float)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(string)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(DateTime)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); CrmActionParameterMainHandle.HandleFactories[typeof(bool)] = DIContainerContainer.Get <CrmActionParameterHandleForOtherFactory>(); }
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); } });
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); }
public ICoroutineService Create() { return(DIContainerContainer.Get <CoroutineServiceForCurrentThread>()); }
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; } }
private async Task DoProcessReceive(SocketAsyncEventArgs e, bool useSocket = false, byte[] buffer = null) { TcpDuplexAcceptContext token = (TcpDuplexAcceptContext)e.UserToken; var innerResult = await InnerDoProcessReceive(e, useSocket, buffer); while (!innerResult.Complete) { innerResult = await InnerDoProcessReceive(e, true, innerResult.Buffer); } //如果收到的是空字节,表示客户端已经关闭,服务端也需要关闭 if (token.RequestData.Count == 0) { lock (token.LockObj) { token.Status = -1; } token.ReleaseReceiveSemaphore(); token.ReleaseSendSemaphore(); return; } if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out IFactory <ITcpDuplexDataExecute> tcpDataExecuteFactory)) { lock (_tcpDuplexDataExecuteFactories) { Type tcpDataExecuteFactoryType = Type.GetType(_listener.ExecuteDataFactoryType); if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out tcpDataExecuteFactory)) { object objTcpDataExecuteFactory; if (_listener.ExecuteDataFactoryTypeUseDI == true) { //通过DI容器创建 objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType); } else { //通过反射创建 objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName); } if (!(objTcpDataExecuteFactory is IFactory <ITcpDataExecute>)) { var fragment = new TextFragment() { Code = TextCodes.TcpDuplexDataExecuteTypeError, DefaultFormatting = "双工Tcp监听{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpDuplexDataExecute>", ReplaceParameters = new List <object>() { _listener.Name, _listener.ExecuteDataFactoryType } }; throw new UtilityException((int)Errors.TcpDuplexDataExecuteTypeError, fragment); } tcpDataExecuteFactory = (IFactory <ITcpDuplexDataExecute>)objTcpDataExecuteFactory; _tcpDuplexDataExecuteFactories.Add(_listener.ExecuteDataFactoryType, tcpDataExecuteFactory); } } } var tcpDataExecute = tcpDataExecuteFactory.Create(); var byteResult = await tcpDataExecute.Execute(token.RequestData.ToArray(), token.Connection, GetConnections()); //标识处理状态为成功,并停止计时 token.ExecuteSuccess = true; token.Watch.Stop(); await AddLog(token); //更新状态,解除接收锁 token.LatestRunning = DateTime.UtcNow; token.RequestData.Clear(); token.RequestData.AddRange(byteResult.RestRequestData); lock (token.LockObj) { token.Status = 1; } token.ReleaseReceiveSemaphore(); //向要发送的连接发送返回信息 if (byteResult.ResponseData != null && byteResult.ResponseData.Length > 0) { List <TcpDuplexAcceptContext> sendContexts = null; if (byteResult.ResponseAll) { sendContexts = GetAllAcceptContext(); } else { sendContexts = GetAcceptContext(byteResult.ResponseConnections); } if (sendContexts != null) { foreach (var itemSendContext in sendContexts) { await itemSendContext.ReceiveSemaphore.WaitAsync(); itemSendContext.SocketAsyncEventArgs.SetBuffer(byteResult.ResponseData, 0, byteResult.ResponseData.Length); try { var willRaiseEvent = itemSendContext.SocketAsyncEventArgs.AcceptSocket.SendAsync(itemSendContext.SocketAsyncEventArgs); if (!willRaiseEvent) { await ProcessSend(itemSendContext.SocketAsyncEventArgs); } } catch (Exception ex) { CloseClientSocket(itemSendContext.SocketAsyncEventArgs); await AddLog($"Send Error,message:{ex.Message},stack:{ex.StackTrace}", DateTime.UtcNow); LoggerHelper.LogError(LogCategoryName, $"TcpDuplexListener {_listener.Name},Send Error,message:{ex.Message},stack:{ex.StackTrace}"); } } } } }
public async Task Start(TcpDuplexListener listener) { if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out IFactory <ITcpDuplexDataExecute> tcpDataExecuteFactory)) { lock (_tcpDuplexDataExecuteFactories) { Type tcpDataExecuteFactoryType = Type.GetType(_listener.ExecuteDataFactoryType); if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out tcpDataExecuteFactory)) { object objTcpDataExecuteFactory; if (_listener.ExecuteDataFactoryTypeUseDI == true) { //通过DI容器创建 objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType); } else { //通过反射创建 objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName); } if (!(objTcpDataExecuteFactory is IFactory <ITcpDataExecute>)) { var fragment = new TextFragment() { Code = TextCodes.TcpDuplexDataExecuteTypeError, DefaultFormatting = "双工Tcp监听{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpDuplexDataExecute>", ReplaceParameters = new List <object>() { _listener.Name, _listener.ExecuteDataFactoryType } }; throw new UtilityException((int)Errors.TcpDuplexDataExecuteTypeError, fragment); } tcpDataExecuteFactory = (IFactory <ITcpDuplexDataExecute>)objTcpDataExecuteFactory; _tcpDuplexDataExecuteFactories.Add(_listener.ExecuteDataFactoryType, tcpDataExecuteFactory); } } } _listener = listener; if (!_start) { //设置监听Socket IPEndPoint localPoint = new IPEndPoint(IPAddress.Any, listener.Port); _listenSocket = new Socket(SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(localPoint); _listenSocket.Listen(listener.MaxConcurrencyCount); //设置连接参数池 _tcpDuplexAcceptContextPool = new Pool <TcpDuplexAcceptContext>($"TcpDuplexListener-{listener.Name}-AcceptContexts", null, null, null, null, async() => { var connection = new TcpDuplexListenerConnection(Guid.NewGuid(), await tcpDataExecuteFactory.Create().GetInitExtensionInfo()); var context = new TcpDuplexAcceptContext(connection.ID) { ListenSocket = _listenSocket, Connection = connection }; var acceptEventArg = new SocketAsyncEventArgs() { UserToken = context }; acceptEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); context.SocketAsyncEventArgs = acceptEventArg; return(await Task.FromResult(context)); }, async(item) => { return(await Task.FromResult(true)); }, null, null , listener.MaxConcurrencyCount); _start = true; //启动定时检查Tcp连接 var t = Task.Run(async() => { while (_start) { try { await ValidateConnection(); } catch (Exception ex) { LoggerHelper.LogError(LogCategoryName, $"TcpDuplexListener {_listener.Name},ValidateConnection Error,message:{ex.Message},stack:{ex.StackTrace}"); } System.Threading.Thread.Sleep(100); } }); await StartAccept(_listenSocket); } }
/// <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)); }
private async Task DoProcessReceive(SocketAsyncEventArgs e, bool useSocket = false, byte[] buffer = null) { TcpAcceptContext token = (TcpAcceptContext)e.UserToken; var innerResult = await InnerDoProcessReceive(e, useSocket, buffer); while (!innerResult.Complete) { innerResult = await InnerDoProcessReceive(e, true, innerResult.Buffer); } bool willRaiseEvent; //处理接收到的数据 var strData = UTF8Encoding.UTF8.GetString(token.RetrieveBytes.ToArray()); //创建接收处理上下文 //检查是否是心跳包 //心跳包的格式固定为字符串“HeartBeat” if (strData.ToLower() == _listener.HeartBeatSendData.ToLower()) { //标识处理状态为成功,并停止计时 token.ExecuteSuccess = true; token.Watch.Stop(); await AddLog(token); token.LatestRunning = DateTime.UtcNow; var responseBytes = UTF8Encoding.UTF8.GetBytes(_emptyResponse); e.SetBuffer(responseBytes, 0, responseBytes.Length); willRaiseEvent = e.AcceptSocket.SendAsync(e); if (!willRaiseEvent) { await ProcessSend(e); } return; } //如果收到的是空字节,表示客户端已经关闭,服务端也需要关闭 if (token.RetrieveBytes.Count == 0) { lock (token.LockObj) { token.Status = -1; } token.ReleaseReceiveSemaphore(); return; } if (!_tcpDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out IFactory <ITcpDataExecute> tcpDataExecuteFactory)) { lock (_tcpDataExecuteFactories) { Type tcpDataExecuteFactoryType = Type.GetType(_listener.ExecuteDataFactoryType); if (!_tcpDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out tcpDataExecuteFactory)) { object objTcpDataExecuteFactory; if (_listener.ExecuteDataFactoryTypeUseDI == true) { //通过DI容器创建 objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType); } else { //通过反射创建 objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName); } if (!(objTcpDataExecuteFactory is IFactory <ITcpDataExecute>)) { var fragment = new TextFragment() { Code = TextCodes.TcpDataExecuteTypeError, DefaultFormatting = "Tcp监听{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpDataExecute>", ReplaceParameters = new List <object>() { _listener.Name, _listener.ExecuteDataFactoryType } }; throw new UtilityException((int)Errors.TcpDataExecuteTypeError, fragment); } tcpDataExecuteFactory = (IFactory <ITcpDataExecute>)objTcpDataExecuteFactory; _tcpDataExecuteFactories.Add(_listener.ExecuteDataFactoryType, tcpDataExecuteFactory); } } } var tcpDataExecute = tcpDataExecuteFactory.Create(); var byteResult = await tcpDataExecute.Execute(token.RetrieveBytes.ToArray()); //标识处理状态为成功,并停止计时 token.ExecuteSuccess = true; token.Watch.Stop(); if (byteResult != null) { token.ResponseBytes = byteResult.ToList(); } await AddLog(token); //发送返回值 if (byteResult != null) { /*var bytes = UTF8Encoding.UTF8.GetBytes(strResult); * * var totalByteList = bytes.Length.ToBytes().ToList(); * * totalByteList.AddRange(bytes); * * var totalBytes = totalByteList.ToArray();*/ e.SetBuffer(byteResult, 0, byteResult.Length); } else { var responseBytes = UTF8Encoding.UTF8.GetBytes(_emptyResponse); e.SetBuffer(responseBytes, 0, responseBytes.Length); } willRaiseEvent = e.AcceptSocket.SendAsync(e); if (!willRaiseEvent) { await ProcessSend(e); } }