Example #1
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);
        }
Example #2
0
        public async Task Invoke(HttpContext context)
        {
            var logger = _loggerFactory.CreateLogger(_categoryName);
            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                using (var diContainer = DIContainerContainer.CreateContainer())
                {
                    ContextContainer.SetValue <IDIContainer>(_name, diContainer);

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

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


                                await InnerInvoke(context);


                                responseStream.Position = 0;
                                await responseStream.CopyToAsync(originalBody);
                            }
                        }
                        finally
                        {
                            context.Response.Body = originalBody;
                        }
                    }
                    else
                    {
                        await InnerInvoke(context);
                    }
                }
            });
        }
Example #3
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();
        }
Example #4
0
        public void Dispose()
        {
            if (_orgServiceCreate)
            {
                var orgService          = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
                var orgServiceDiposable = orgService as IDisposable;

                if (orgServiceDiposable != null)
                {
                    using (orgServiceDiposable)
                    {
                    }
                }

                ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, null);
            }

            if (_dictionaryCreate)
            {
                var dict    = ContextContainer.GetValue <Dictionary <string, object> >(ContextTypes.Dictionary);
                var strDict = BinarySerializerHelper.Serializer <Dictionary <string, object> >(dict);
                _context.SharedVariables["dictionary"] = strDict;

                ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, null);
            }

            if (_currentUserCreate)
            {
                ContextContainer.SetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser, null);
            }

            if (_currentOrganizationCreate)
            {
                ContextContainer.SetValue <Guid>(ContextTypes.CurrentOrganization, Guid.Empty);
            }

            if (_orgServiceFactoryCreate)
            {
                ContextContainer.SetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory, null);
            }

            if (_tracingServiceCreate)
            {
                ContextContainer.SetValue <IConfigurationService>(ContextTypes.TracingService, null);
            }
        }
Example #5
0
        public void Do(IEnumerable <Claim> claims)
        {
            var defaultContextInfoConfig = _systemConfigurationRepository.QueryByName(SystemConfigurationNames.DefaultContextInfo);

            if (defaultContextInfoConfig == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundSystemConfigurationByName,
                    DefaultFormatting = "找不到名称为{0}的系统配置",
                    ReplaceParameters = new List <object>()
                    {
                        SystemConfigurationNames.DefaultContextInfo
                    }
                };
                throw new UtilityException((int)Errors.NotFoundSystemConfigurationByName, fragment);
            }

            var contextInfo = defaultContextInfoConfig.GetConfigurationValue <DefaultContextInfo>();

            if (contextInfo == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.SystemConfigurationConvertTypeFail,
                    DefaultFormatting = "系统配置{0}转成类型{1}失败,配置内容为{2}",
                    ReplaceParameters = new List <object>()
                    {
                        SystemConfigurationNames.DefaultContextInfo, typeof(DefaultContextInfo).FullName, defaultContextInfoConfig.Content
                    }
                };
                throw new UtilityException((int)Errors.SystemConfigurationConvertTypeFail, fragment);
            }

            ContextContainer.SetValue <string>(ContextTypes.CurrentUserId, contextInfo.UserID);
            ContextContainer.SetValue <int>(ContextTypes.CurrentUserLcid, contextInfo.Lcid);
            ContextContainer.SetValue <int>(ContextTypes.CurrentUserTimezoneOffset, contextInfo.TimezoneOffset);
            ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, new Dictionary <string, object>());
        }
Example #6
0
        public async Task <bool> Execute(HttpContext context)
        {
            bool   result            = true;
            Guid   parentID          = Guid.NewGuid();
            Guid   preLevelID        = Guid.Empty;
            Guid   currentLevelID    = Guid.NewGuid();
            string parentActionName  = context.Request.Path;
            string parentContextInfo = string.Empty;

            if (context.Request.Headers.TryGetValue(HttpHeaderNames.LogInfo, out StringValues strLogInfo))
            {
                var parentLogInfo = JsonSerializerHelper.Deserialize <ParentLogInfo>(strLogInfo[0]);
                if (parentLogInfo != null && parentLogInfo.ParentID != Guid.Empty)
                {
                    result     = false;
                    parentID   = parentLogInfo.ParentID;
                    preLevelID = parentLogInfo.PreLevelID;

                    if (!string.IsNullOrEmpty(parentLogInfo.ParentActionName))
                    {
                        parentActionName = parentLogInfo.ParentActionName;
                    }

                    if (!string.IsNullOrEmpty(parentLogInfo.ContextInfo))
                    {
                        parentContextInfo = parentLogInfo.ContextInfo;
                    }
                }
            }

            ContextContainer.SetValue(ContextExtensionTypes.ParentCommonLogID, parentID);
            ContextContainer.SetValue(ContextExtensionTypes.ParentCommonLogActionName, parentActionName);
            ContextContainer.SetValue(ContextExtensionTypes.ParentCommonLogContextInfo, parentContextInfo);
            ContextContainer.SetValue(ContextExtensionTypes.PreCommonLogLevelID, preLevelID);
            ContextContainer.SetValue(ContextExtensionTypes.CurrentCommonLogLevelID, currentLevelID);

            return(await Task.FromResult(result));
        }
        public void Do(IEnumerable <Claim> claims)
        {
            //获取用户ID
            var strUserID = (from item in claims
                             where item.Type == ClaimsTypes.UserID
                             select item.Value).FirstOrDefault();

            if (!string.IsNullOrEmpty(strUserID))
            {
                ContextContainer.SetValue <string>(ContextTypes.CurrentUserId, strUserID);
            }
            else
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundTypeInClaims,
                    DefaultFormatting = "找不到类型为{0}的声明,发生位置:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        ContextTypes.CurrentUserId, $"{this.GetType().FullName}.Do"
                    }
                };
                throw new UtilityException((int)Errors.NotFoundTypeInClaims, fragment);
            }

            //获取Lcid
            var strLcid = (from item in claims
                           where item.Type == ClaimsTypes.Lcid
                           select item.Value).FirstOrDefault();

            if (!string.IsNullOrEmpty(strLcid))
            {
                ContextContainer.SetValue <int>(ContextTypes.CurrentUserLcid, Int32.Parse(strLcid));
            }
            else
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundTypeInClaims,
                    DefaultFormatting = "找不到类型为{0}的声明,发生位置:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        ContextTypes.CurrentUserLcid, $"{this.GetType().FullName}.Do"
                    }
                };
                throw new UtilityException((int)Errors.NotFoundTypeInClaims, fragment);
            }

            //获取TimezoneOffset
            var strTO = (from item in claims
                         where item.Type == ClaimsTypes.TimezoneOffset
                         select item.Value).FirstOrDefault();

            if (!string.IsNullOrEmpty(strLcid))
            {
                ContextContainer.SetValue <int>(ContextTypes.CurrentUserTimezoneOffset, Int32.Parse(strTO));
            }
            else
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundTypeInClaims,
                    DefaultFormatting = "找不到类型为{0}的声明,发生位置:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        ContextTypes.CurrentUserTimezoneOffset, $"{this.GetType().FullName}.Do"
                    }
                };
                throw new UtilityException((int)Errors.NotFoundTypeInClaims, fragment);
            }

            //增加字典上下文
            ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, new Dictionary <string, object>());
        }
        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);
        }
Example #9
0
        /// <summary>
        /// 执行所有关联的队列
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public async Task <ISQueueProcessGroupExecuteResult> Execute(SQueueProcessGroup group)
        {
            bool errorLogRecord = false;
            //声明一个轮询配置列表,队列的执行通过轮询处理帮助器管理,保证只有一个主控线程被占用
            List <PollingConfiguration> pollingConfigurations = new List <PollingConfiguration>();

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

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

                                var claims = await administratorClaimGenerator.Generate();

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

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

                                administratorClaimContextGenerator.ContextInit(claims.Claims);
                            }

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

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


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

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

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

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

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

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

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

                await Task.FromResult(0);
            });

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

            return(new SQueueProcessGroupExecuteResultDefalut(pollingResult));
        }
Example #10
0
        public IWorkflowContextController Init(CodeActivityContext codeActivityContext)
        {
            bool dictionaryCreate          = false;
            bool orgServiceCreate          = false;
            bool tracingServiceCreate      = false;
            bool currentUserCreate         = false;
            bool currentOrganizationCreate = false;
            bool orgServiceFactoryCreate   = false;

            IWorkflowContext            wfContext = codeActivityContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory sFactory  = codeActivityContext.GetExtension <IOrganizationServiceFactory>();
            IWorkflowContext            workContext;

            workContext = wfContext;

            while (workContext.ParentContext != null)
            {
                workContext = workContext.ParentContext;
            }


            //获取当前用户
            var currentUser = ContextContainer.GetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser);
            //获取当前组织编号
            var currentOrganization = ContextContainer.GetValue <Guid>(ContextTypes.CurrentOrganization);
            //获取dictorany
            var dict = ContextContainer.GetValue <Dictionary <string, object> >(ContextTypes.Dictionary);
            //获取orgService
            var orgService       = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
            var isAutoOrgService = ContextContainer.IsAuto <IOrganizationService>(ContextTypes.OrgService.ToString());
            //获取orgServiceFactory
            var orgServiceFactory = ContextContainer.GetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory);
            //获取tracingService
            var tracingService = ContextContainer.GetValue <ITracingService>(ContextTypes.TracingService);



            //新建所有上下文
            if (currentUser == null || ContextContainer.IsAuto <ICurrentUserInfoContext>(ContextTypes.CurrentUser))
            {
                currentUserCreate = true;
                ContextContainer.SetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser, CurrentUserInfoContextFactory.Get().Create(workContext.InitiatingUserId));
            }


            if (currentOrganization == Guid.Empty || ContextContainer.IsAuto <Guid>(ContextTypes.CurrentOrganization))
            {
                currentOrganizationCreate = true;
                ContextContainer.SetValue <Guid>(ContextTypes.CurrentOrganization, workContext.OrganizationId);
            }

            if (tracingService == null || ContextContainer.IsAuto <ITracingService>(ContextTypes.TracingService))
            {
                tracingServiceCreate = true;
                ContextContainer.SetValue <ITracingService>(ContextTypes.TracingService, codeActivityContext.GetExtension <ITracingService>());
            }


            if (dict == null || ContextContainer.IsAuto <Dictionary <string, object> >(ContextTypes.Dictionary))
            {
                dictionaryCreate = true;
                if (workContext.SharedVariables.Contains("dictionary"))
                {
                    var dictionary = BinarySerializerHelper.Deserialize <Dictionary <string, object> >(workContext.SharedVariables["dictionary"].ToString());

                    ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, dictionary);

                    dict = dictionary;
                }
                else
                {
                    dict = new Dictionary <string, object>();
                    ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, dict);
                }
            }


            lock (dict)
            {
                dict[ContextDictionaryKeys.OrgName] = workContext.OrganizationName;
            }

            if (orgService == null || isAutoOrgService)
            {
                orgServiceCreate = true;
                //获取临时OrgService
                var tempOrgService          = sFactory.CreateOrganizationService(workContext.InitiatingUserId);
                var tempOrgServiceDiposable = tempOrgService as IDisposable;

                if (tempOrgServiceDiposable != null)
                {
                    using (tempOrgServiceDiposable)
                    {
                        ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, tempOrgService);
                        EntityReference administratorId = _configurationService.GetAdministratorID();
                        orgService = sFactory.CreateOrganizationService(administratorId.Id);

                        ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, orgService);
                    }
                }
                else
                {
                    ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, tempOrgService);
                    EntityReference administratorId = _configurationService.GetAdministratorID();
                    orgService = sFactory.CreateOrganizationService(administratorId.Id);

                    ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, orgService);
                }
            }



            if (orgServiceFactory == null || ContextContainer.IsAuto <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory))
            {
                orgServiceFactoryCreate = true;
                ContextContainer.SetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory, sFactory);
            }


            return(new WorkflowContextController(workContext, dictionaryCreate, orgServiceCreate, tracingServiceCreate, currentUserCreate, currentOrganizationCreate, orgServiceFactoryCreate));
        }
Example #11
0
            public async Task Execute(IJobExecutionContext context)
            {
                //获取调度动作名称
                var actionName = context.JobDetail.JobDataMap.GetString("ActionName");
                //获取调度动作名称
                var groupName = context.JobDetail.JobDataMap.GetString("GroupName");
                //获取初始化类型
                var initType = context.JobDetail.JobDataMap.GetString("InitType");
                //获取初始化配置
                var initConfiguration = context.JobDetail.JobDataMap.GetString("InitConfiguration");


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

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

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


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

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

                                initService.Init();

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

                                runStatus.Result = actionResult;

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

                                    if (_useLog)
                                    {
                                        LoggerHelper.LogInformation(_informationCategory, $"ScheduleAction {actionName} in Grioup {groupName} stop");
                                    }
                                }
                            }
                            finally
                            {
                                ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.LogError(_errorCategory, $"ScheduleAction {actionName} in Grioup {groupName} start error,detail:{ex.Message},stacktrace:{ex.StackTrace}");
                    //throw;
                }
            }
Example #12
0
        static void Main(string[] args)
        {
            StartupMain.Start();


            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

            var crmServiceUrl = "https://lap4.api.crm5.dynamics.com/XRMServices/2011/Organization.svc";
            var userName      = "******";
            var password      = "******";

            var orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(crmServiceUrl));

            AuthenticationProviderType endpointType = orgServiceManagement.AuthenticationType;

            AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType, "", userName, password);

            AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(credentials);


            OrganizationServiceProxy proxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);



            ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, proxy);


            var record = PAEntityRepositoryFactory.Get().QueryByID("ms_test", Guid.Parse("3EE7916F-0A5A-EA11-A811-000D3A854084"), "ms_name");


            record.DownloadAttributeFile("ms_file", (name, stream) =>
            {
                List <byte> total = new List <byte>();
                int size          = 1000;
                int cSize         = size;
                byte[] buff       = new byte[size];
                while (cSize == size)
                {
                    cSize = stream.Read(buff, 0, size);
                    total.AddRange(buff.Take(cSize).ToList());
                }

                var str = UTF8Encoding.UTF8.GetString(total.ToArray());
            });


            using (var stream = File.OpenRead("D:\\2.txt"))
            {
                record.UploadAttributeFile("ms_file", "test.txt", "application/octet-stream", stream);
            }


            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, 9800));

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression();

            entityQueryExpression.Criteria = EntityFilter;
            //entityQueryExpression.AttributeQuery=new AttributeQueryExpression()

            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression,

                //ClientVersionStamp = clientVersionStamp,
                //DeletedMetadataFilters = deletedMetadataFilter
            };

            var response = proxy.Execute(retrieveMetadataChangesRequest);

            var strFetch = string.Format(@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"">
                                <entity name=""webresource"">
                                    <attribute name=""content"" />
                                    <attribute name=""description"" />
                                    <attribute name=""languagecode"" />
                                    <attribute name=""webresourcetype"" />   
                                    <filter type=""and"">
                                        <condition attribute=""name"" operator=""eq"" value=""{0}"" />
                                    </filter>
                                </entity>
                            </fetch>", "ms_testjson");


            var result = proxy.RetrieveMultiple(new FetchExpression(strFetch));
        }
Example #13
0
 public FunctionBase(IServiceProvider serviceProvider, params object[] parameters)
 {
     ContextContainer.SetValue(ContextTypes.ServiceProvider, serviceProvider);
     FunctionInitLoad.Init(parameters);
 }