예제 #1
0
        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();
            }
        }
예제 #2
0
        /// <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();
        }
예제 #3
0
        /// <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);
        }
예제 #4
0
        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;
        }
예제 #5
0
        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);
        }
 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));
     }
 }
예제 #7
0
파일: GrpcHost.cs 프로젝트: rhw1111/DCEM
        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();
        }
예제 #8
0
        //执行之前处理
        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();
        }
예제 #9
0
        /// <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();
        }
예제 #10
0
        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());
        }
        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));
        }
예제 #12
0
        private async Task DoProcessReceive(SocketAsyncEventArgs e, bool useSocket = false, byte[] buffer = null)
        {
            var context = (TcpClientContext)e.UserToken;

            var innerResult = await InnerDoProcessReceive(e, useSocket, buffer);

            while (!innerResult.Complete)
            {
                innerResult = await InnerDoProcessReceive(e, true, innerResult.Buffer);
            }

            //处理接收到的数据
            //var strData = UTF8Encoding.UTF8.GetString(context.ReceiveBytes.ToArray());



            if (!_tcpDataExecuteFactories.TryGetValue(_endpoint.ExecuteDataFactoryType, out IFactory <ITcpClientDataExecute> tcpDataExecuteFactory))
            {
                lock (_tcpDataExecuteFactories)
                {
                    Type tcpDataExecuteFactoryType = Type.GetType(_endpoint.ExecuteDataFactoryType);

                    if (!_tcpDataExecuteFactories.TryGetValue(_endpoint.ExecuteDataFactoryType, out tcpDataExecuteFactory))
                    {
                        object objTcpDataExecuteFactory;
                        if (_endpoint.ExecuteDataFactoryTypeUseDI == true)
                        {
                            //通过DI容器创建
                            objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType);
                        }
                        else
                        {
                            //通过反射创建
                            objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName);
                        }

                        if (!(objTcpDataExecuteFactory is IFactory <ITcpClientDataExecute>))
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.TcpClientDataExecuteTypeError,
                                DefaultFormatting = "Tcp客户端{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpClientDataExecute>",
                                ReplaceParameters = new List <object>()
                                {
                                    _endpoint.Name, _endpoint.ExecuteDataFactoryType
                                }
                            };

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

                        tcpDataExecuteFactory = (IFactory <ITcpClientDataExecute>)objTcpDataExecuteFactory;
                        _tcpDataExecuteFactories.Add(_endpoint.ExecuteDataFactoryType, tcpDataExecuteFactory);
                    }
                }
            }

            var tcpDataExecute = tcpDataExecuteFactory.Create();

            var receiceResult = await tcpDataExecute.ReceiveExecute(context.ReceiveBytes.ToArray());

            if (receiceResult.Exception == null)
            {
                context.ReceiveException = null;
                context.ReceiveBytes.Clear();
                context.ReceiveBytes.AddRange(receiceResult.Data);
                context.ReceiveSemaphore.Release();
            }
            else
            {
                context.ReceiveException = receiceResult.Exception;
                context.ReceiveSemaphore.Release();
                await CloseConnection(receiceResult.Exception);
            }
        }
예제 #13
0
        /// <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>();
        }
예제 #14
0
        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}");
                        }
                    }
                }
            }
        }
예제 #15
0
        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);
            }
        }
예제 #16
0
        public ActionResult <IEnumerable <string> > Get()
        {
            var service = DIContainerContainer.Get <CrmService>();

            return(new string[] { "value1", "value2" });
        }
예제 #17
0
파일: TcpListener.cs 프로젝트: rhw1111/DCEM
        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);
            }
        }
예제 #18
0
 public ICoroutineService Create()
 {
     return(DIContainerContainer.Get <CoroutineServiceForCurrentThread>());
 }