public virtual IVariableInstance Execute(ICommandContext commandContext)
        {
            if (taskId is null)
            {
                throw new ActivitiIllegalArgumentException("taskId is null");
            }
            if (variableName is null)
            {
                throw new ActivitiIllegalArgumentException("variableName is null");
            }

            ITaskEntity task = commandContext.TaskEntityManager.FindById <ITaskEntity>(taskId);

            if (task == null)
            {
                throw new ActivitiObjectNotFoundException("task " + taskId + " doesn't exist", typeof(ITask));
            }

            IVariableInstance variableEntity;

            if (isLocal)
            {
                variableEntity = task.GetVariableInstanceLocal(variableName, false);
            }
            else
            {
                variableEntity = task.GetVariableInstance(variableName, false);
            }

            return(variableEntity);
        }
 public virtual void AddCandidateUsers(ITaskEntity taskEntity, IEnumerable <string> candidateUsers)
 {
     foreach (string candidateUser in candidateUsers)
     {
         AddCandidateUser(taskEntity, candidateUser);
     }
 }
示例#3
0
        public virtual ITask[] Execute(ICommandContext commandContext)
        {
            if (users == null)
            {
                throw new ActivitiException("There are no personnel to be assigned.");
            }

            var           taskService   = commandContext.ProcessEngineConfiguration.TaskService;
            var           processConfig = commandContext.ProcessEngineConfiguration;
            IList <ITask> tasks         = new List <ITask>();

            foreach (var user in users)
            {
                ITaskEntity task = commandContext.TaskEntityManager.FindById <ITaskEntity>(user.TaskId);
                taskService.Unclaim(user.TaskId);
                taskService.Claim(user.TaskId, user.To);
                tasks.Add(task);
                //if (string.IsNullOrWhiteSpace(user.BusinessKey) == false)
                //{
                //    IList<IExecution> executions = processConfig.RuntimeService.CreateExecutionQuery()
                //        .SetProcessInstanceBusinessKey(user.BusinessKey)
                //        .List();

                //}
                //else if (string.IsNullOrWhiteSpace(user.TaskId) == false)
                //{
                //}
                //else
                //{
                //    throw new ActivitiException("must input businessKey or taskId.");
                //}
            }

            return(tasks.ToArray());
        }
 public virtual void AddCandidateGroups(ITaskEntity taskEntity, IEnumerable <string> candidateGroups)
 {
     foreach (string candidateGroup in candidateGroups)
     {
         AddCandidateGroup(taskEntity, candidateGroup);
     }
 }
示例#5
0
 public CustomTaskCompletedEntityEventImpl(ITaskEntity entity, ActivitiEventType type) :
     base(entity, type)
 {
     ExecutionId         = entity.ExecutionId;
     ProcessInstanceId   = entity.ProcessInstanceId;
     ProcessDefinitionId = entity.ProcessDefinitionId;
 }
示例#6
0
        protected internal override T1 Execute(ICommandContext commandContext, ITaskEntity task)
        {
            if (isLocal)
            {
                if (variables != null)
                {
                    foreach (string variableName in variables.Keys)
                    {
                        task.SetVariableLocal(variableName, variables[variableName], false);
                    }
                }
            }
            else
            {
                if (variables != null)
                {
                    foreach (string variableName in variables.Keys)
                    {
                        task.SetVariable(variableName, variables[variableName], false);
                    }
                }
            }

            // ACT-1887: Force an update of the task's revision to prevent
            // simultaneous inserts of the same variable. If not, duplicate variables may occur since optimistic
            // locking doesn't work on inserts
            task.ForceUpdate();

            return(default);
示例#7
0
        public virtual void ExecuteTaskListeners(UserTask userTask, ITaskEntity taskEntity, string eventType)
        {
            foreach (ActivitiListener activitiListener in userTask.TaskListeners)
            {
                string @event = activitiListener.Event;
                if (@event.Equals(eventType) || @event.Equals(BaseTaskListenerFields.EVENTNAME_ALL_EVENTS))
                {
                    IBaseTaskListener taskListener = CreateTaskListener(activitiListener);

                    if (activitiListener.OnTransaction is object)
                    {
                        PlanTransactionDependentTaskListener(taskEntity.Execution, (ITransactionDependentTaskListener)taskListener, activitiListener);
                    }
                    else
                    {
                        taskEntity.EventName = eventType;
                        taskEntity.CurrentActivitiListener = activitiListener;
                        try
                        {
                            Context.ProcessEngineConfiguration.DelegateInterceptor.HandleInvocation(new TaskListenerInvocation((ITaskListener)taskListener, taskEntity));
                        }
                        catch (Exception e)
                        {
                            throw new ActivitiException("Exception while invoking TaskListener: " + e.Message, e);
                        }
                        finally
                        {
                            taskEntity.EventName = null;
                            taskEntity.CurrentActivitiListener = null;
                        }
                    }
                }
            }
        }
示例#8
0
        public virtual IComment Execute(ICommandContext commandContext)
        {
            // Validate task
            if (!(taskId is null))
            {
                ITaskEntity task = commandContext.TaskEntityManager.FindById <ITaskEntity>(taskId);

                if (task == null)
                {
                    logger.LogWarning("Cannot find task with id " + taskId, typeof(ITask));
                    return(null);
                }

                if (task.Suspended)
                {
                    throw new ActivitiException(SuspendedTaskException);
                }
            }

            if (!(processInstanceId is null))
            {
                IExecutionEntity execution = commandContext.ExecutionEntityManager.FindById <IExecutionEntity>(processInstanceId);

                if (execution == null)
                {
                    logger.LogWarning("Cannot find task with id " + taskId, typeof(ITask));
                    return(null);
                    //throw new ActivitiObjectNotFoundException("execution " + processInstanceId + " doesn't exist", typeof(IExecution));
                }

                if (execution.Suspended)
                {
                    throw new ActivitiException(SuspendedExceptionMessage);
                }
            }

            IUserInfo      user    = Authentication.AuthenticatedUser;
            ICommentEntity comment = commandContext.CommentEntityManager.Create();

            comment.UserId            = user.Id;
            comment.Type              = (type is null) ? CommentEntityFields.TYPE_COMMENT : type;
            comment.Time              = commandContext.ProcessEngineConfiguration.Clock.CurrentTime;
            comment.TaskId            = taskId;
            comment.ProcessInstanceId = processInstanceId;
            comment.Action            = EventFields.ACTION_ADD_COMMENT;

            string eventMessage = message.Replace("\\s+", " ");

            if (eventMessage.Length > 163)
            {
                eventMessage = eventMessage.Substring(0, 160) + "...";
            }
            comment.Message = eventMessage;

            comment.FullMessage = message;

            commandContext.CommentEntityManager.Insert(comment);

            return(comment);
        }
        public override IEventLogEntryEntity GenerateEventLogEntry(CommandContext <IEventLogEntryEntity> commandContext)
        {
            IActivitiEntityEvent activitiEntityEvent = (IActivitiEntityEvent)@event;

            ITaskEntity task = (ITaskEntity)activitiEntityEvent.Entity;
            IDictionary <string, object> data = handleCommonTaskFields(task);

            long duration = timeStamp.Value.Ticks - task.CreateTime.Value.Ticks;

            PutInMapIfNotNull(data, FieldsFields.DURATION, duration);

            if (@event is IActivitiEntityWithVariablesEvent)
            {
                IActivitiEntityWithVariablesEvent activitiEntityWithVariablesEvent = (IActivitiEntityWithVariablesEvent)@event;
                if (activitiEntityWithVariablesEvent.Variables != null && activitiEntityWithVariablesEvent.Variables.Count > 0)
                {
                    IDictionary <string, object> variableMap = new Dictionary <string, object>();
                    foreach (object variableName in activitiEntityWithVariablesEvent.Variables.Keys)
                    {
                        PutInMapIfNotNull(variableMap, (string)variableName, activitiEntityWithVariablesEvent.Variables[variableName.ToString()]);
                    }
                    if (activitiEntityWithVariablesEvent.LocalScope)
                    {
                        PutInMapIfNotNull(data, FieldsFields.LOCAL_VARIABLES, variableMap);
                    }
                    else
                    {
                        PutInMapIfNotNull(data, FieldsFields.VARIABLES, variableMap);
                    }
                }
            }

            return(CreateEventLogEntry(task.ProcessDefinitionId, task.ProcessInstanceId, task.ExecutionId, task.Id, data));
        }
        public override IEventLogEntryEntity GenerateEventLogEntry(CommandContext <IEventLogEntryEntity> commandContext)
        {
            ITaskEntity task = (ITaskEntity)((IActivitiEntityEvent)@event).Entity;
            IDictionary <string, object> data = handleCommonTaskFields(task);

            return(CreateEventLogEntry(task.ProcessDefinitionId, task.ProcessInstanceId, task.ExecutionId, task.Id, data));
        }
示例#11
0
        private void Transfer(ICommandContext commandContext)
        {
            ITaskService taskService = commandContext.ProcessEngineConfiguration.TaskService;

            ITaskEntity task = taskService.CreateTaskQuery().SetTaskId(taskCmd.TaskId).SingleResult() as ITaskEntity;

            if (task == null)
            {
                throw new ActivitiObjectNotFoundException("Parent task with id " + taskCmd.TaskId + " was not found");
            }

            //查找当前待追加人员是否已经存在在任务列表中,proc_inst_id_
            IList <ITask> assignTasks = taskService.CreateTaskQuery()
                                        .SetProcessInstanceId(task.ProcessInstanceId)
                                        .SetTaskAssigneeIds(taskCmd.Assignees)
                                        .List();

            var users = taskCmd.Assignees.Where(x => assignTasks.Any(y => x == y.Assignee) == false).ToArray();

            if (users.Length == 0)
            {
                throw new NotFoundAssigneeException();
            }
            else
            {
                tasks = commandContext.ProcessEngineConfiguration.ManagementService.ExecuteCommand(new AddCountersignCmd(task.Id, users, task.TenantId));
            }
        }
示例#12
0
        public virtual bool  Execute(ICommandContext commandContext)
        {
            if (taskId is null)
            {
                throw new ActivitiIllegalArgumentException("taskId is null");
            }
            if (variableName is null)
            {
                throw new ActivitiIllegalArgumentException("variableName is null");
            }

            ITaskEntity task = commandContext.TaskEntityManager.FindById <ITaskEntity>(new KeyValuePair <string, object>("id", taskId));

            if (task == null)
            {
                throw new ActivitiObjectNotFoundException("task " + taskId + " doesn't exist", typeof(ITask));
            }

            bool hasVariable;

            if (isLocal)
            {
                hasVariable = task.HasVariableLocal(variableName);
            }
            else
            {
                hasVariable = task.HasVariable(variableName);
            }

            return(hasVariable);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="event"></param>
        public override void OnEvent(IActivitiEvent @event)
        {
            if (@event is CustomTaskCompletedEntityEventImpl taskEvent)
            {
                ITaskEntity taskEntity = taskEvent.Entity as ITaskEntity;

                ICommandContext commandContext = Context.CommandContext;

                IExecutionEntity execution = taskEntity.Execution;

                UserTask userTask = execution.CurrentFlowElement as UserTask;

                if (userTask.HasMultiInstanceLoopCharacteristics() &&
                    (taskEntity.IsAppend.GetValueOrDefault(false) ||
                     taskEntity.IsTransfer.GetValueOrDefault(false)))
                {
                    IExecutionEntity parent = execution.FindMultiInstanceParentExecution();

                    var collection = userTask.LoopCharacteristics.GetCollectionVarName();

                    IList <string> users = parent.GetLoopVariable <IList <string> >(collection);

                    string usr = users.FirstOrDefault(x => x.Equals(taskEntity.Assignee, StringComparison.OrdinalIgnoreCase));

                    if (usr != null)
                    {
                        users.Remove(usr);
                        parent.SetLoopVariable(collection, users);
                    }
                }
            }
        }
示例#14
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            task.Priority = priority;
            commandContext.HistoryManager.RecordTaskPriorityChange(task.Id, task.Priority);
            commandContext.TaskEntityManager.Update(task);

            return(null);
        }
示例#15
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            task.DueDate = dueDate;
            commandContext.HistoryManager.RecordTaskDueDateChange(task.Id, task.DueDate.GetValueOrDefault());
            commandContext.TaskEntityManager.Update(task);

            return(null);
        }
示例#16
0
 public static void SetSuspensionState(ITaskEntity taskEntity, ISuspensionState state)
 {
     if (taskEntity.SuspensionState == state.StateCode)
     {
         throw new ActivitiException("Cannot set suspension state '" + state + "' for " + taskEntity + "': already in state '" + state + "'.");
     }
     taskEntity.SuspensionState = state.StateCode;
     DispatchStateChangeEvent(taskEntity, state);
 }
        public void 获取已完成流程节点(string bpmnFile)
        {
            string xml = IntegrationTestContext.ReadBpmn(bpmnFile);

            ICommandExecutor commandExecutor = (processEngine.ProcessEngineConfiguration as ProcessEngineConfigurationImpl).CommandExecutor;

            Authentication.AuthenticatedUser = new InProcessWorkflowEngine.TestUser()
            {
                Id       = "评审员",
                FullName = "评审员",
                TenantId = context.TenantId
            };

            IDeploymentBuilder builder = processEngine.RepositoryService.CreateDeployment()
                                         .Name(Path.GetFileNameWithoutExtension(bpmnFile))
                                         .TenantId(context.TenantId)
                                         .AddString(bpmnFile, xml)
                                         .EnableDuplicateFiltering()
                                         .TenantId(context.TenantId);

            IDeployment deploy = commandExecutor.Execute(new DeployCmd(builder));

            IProcessDefinition definition = processEngine.RepositoryService.CreateProcessDefinitionQuery()
                                            .SetDeploymentId(deploy.Id)
                                            .SetProcessDefinitionTenantId(context.TenantId)
                                            .SetLatestVersion()
                                            .SingleResult();

            BpmnModel model = commandExecutor.Execute(new GetBpmnModelCmd(definition.Id));

            IProcessInstance processInstance = commandExecutor.Execute(new StartProcessInstanceCmd(definition.Id, null));

            IList <ITask> tasks = processEngine.TaskService.GetMyTasks("用户1");

            ITaskEntity      task      = tasks[0] as ITaskEntity;
            IExecutionEntity execution = commandExecutor.Execute(new GetExecutionByIdCmd(task.ExecutionId));

            processEngine.TaskService.Complete(task.Id, new Dictionary <string, object>
            {
                { "流程变量", "变量值" }
            });

            var list = commandExecutor.Execute(new GetCompletedTaskModelsCmd(task.ProcessInstanceId, true));

            Assert.Contains(model.MainProcess.FlowElements, x => list.Any(y => x.Id == y.Id));

            tasks = processEngine.TaskService.GetMyTasks("用户2");
            task  = tasks[0] as ITaskEntity;
            processEngine.TaskService.Complete(task.Id, new Dictionary <string, object>
            {
                { "流程变量", "变量值" }
            });

            list = commandExecutor.Execute(new GetCompletedTaskModelsCmd(task.ProcessInstanceId, true));

            Assert.Contains(model.MainProcess.FlowElements, x => list.Any(y => x.Id == y.Id));
        }
示例#18
0
        // Task related history

        /// <summary>
        ///
        /// </summary>
        /// <param name="task"></param>
        /// <param name="execution"></param>
        public virtual void RecordTaskCreated(ITaskEntity task, IExecutionEntity execution)
        {
            if (IsHistoryLevelAtLeast(HistoryLevel.AUDIT))
            {
                IHistoricTaskInstanceEntity historicTaskInstance = HistoricTaskInstanceEntityManager.Create(task, execution);
                HistoricTaskInstanceEntityManager.Insert(historicTaskInstance, false);
            }

            RecordTaskId(task);
        }
示例#19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="task"></param>

        public virtual void RecordTaskClaim(ITaskEntity task)
        {
            if (IsHistoryLevelAtLeast(HistoryLevel.AUDIT))
            {
                IHistoricTaskInstanceEntity historicTaskInstance = HistoricTaskInstanceEntityManager.FindById <IHistoricTaskInstanceEntity>(new KeyValuePair <string, object>("historicTaskInstanceId", task.Id));
                if (historicTaskInstance != null)
                {
                    historicTaskInstance.ClaimTime = task.ClaimTime;
                }
            }
        }
示例#20
0
        public virtual void DeleteVariableInstanceByTask(ITaskEntity task)
        {
            IDictionary <string, IVariableInstanceEntity> variableInstances = task.VariableInstanceEntities;

            if (variableInstances != null)
            {
                foreach (IVariableInstanceEntity variableInstance in variableInstances.Values)
                {
                    Delete(variableInstance);
                }
            }
        }
示例#21
0
 public virtual void ExecuteTaskListeners(ITaskEntity taskEntity, string eventType)
 {
     if (taskEntity.ProcessDefinitionId is object)
     {
         Process     process     = ProcessDefinitionUtil.GetProcess(taskEntity.ProcessDefinitionId);
         FlowElement flowElement = process.GetFlowElement(taskEntity.TaskDefinitionKey, true);
         if (flowElement is UserTask userTask)
         {
             ExecuteTaskListeners(userTask, taskEntity, eventType);
         }
     }
 }
示例#22
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            if (isLocal)
            {
                task.RemoveVariablesLocal(variableNames);
            }
            else
            {
                task.RemoveVariables(variableNames);
            }

            return(null);
        }
示例#23
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="task"></param>
 public virtual void RecordTaskId(ITaskEntity task)
 {
     if (IsHistoryLevelAtLeast(HistoryLevel.ACTIVITY))
     {
         IExecutionEntity execution = task.Execution;
         if (execution != null)
         {
             IHistoricActivityInstanceEntity historicActivityInstance = FindActivityInstance(execution, false, true);
             if (historicActivityInstance != null)
             {
                 historicActivityInstance.TaskId = task.Id;
             }
         }
     }
 }
示例#24
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            bool assignedToNoOne = false;

            if (IdentityLinkType.ASSIGNEE.Equals(identityType))
            {
                string assigneeUser = null;
                if (string.IsNullOrWhiteSpace(identityId) == false)
                {
                    //TODO: 考虑性能问题,暂时不要获取人员信息
                    //assigneeUser = AsyncHelper.RunSync(() => userService.GetUser(identityId))?.FullName;
                }
                commandContext.TaskEntityManager.ChangeTaskAssignee(task, identityId, assigneeUser);
                assignedToNoOne = identityId is null;
            }
            else if (IdentityLinkType.OWNER.Equals(identityType))
            {
                commandContext.TaskEntityManager.ChangeTaskOwner(task, identityId);
            }
            else if (IDENTITY_USER == identityIdType)
            {
                task.AddUserIdentityLink(identityId, identityType);
            }
            else if (IDENTITY_GROUP == identityIdType)
            {
                task.AddGroupIdentityLink(identityId, identityType);
            }

            bool forceNullUserId = false;

            if (assignedToNoOne)
            {
                // ACT-1317: Special handling when assignee is set to NULL, a
                // CommentEntity notifying of assignee-delete should be created
                forceNullUserId = true;
            }

            if (IDENTITY_USER == identityIdType)
            {
                commandContext.HistoryManager.CreateUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId);
            }
            else
            {
                commandContext.HistoryManager.CreateGroupIdentityLinkComment(taskId, identityId, identityType, true);
            }

            return(null);
        }
示例#25
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            task.DelegationState = DelegationState.PENDING;
            if (task.Owner is null)
            {
                task.Owner = task.Assignee;
            }
            string userName = null;

            if (string.IsNullOrWhiteSpace(userId) == false)
            {
                userName = AsyncHelper.RunSync(() => userService.GetUser(userId))?.FullName;
            }
            commandContext.TaskEntityManager.ChangeTaskAssignee(task, userId, userName);
            return(null);
        }
示例#26
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            if (!(userId is null))
            {
                task.ClaimTime = commandContext.ProcessEngineConfiguration.Clock.CurrentTime;

                if (!(task.Assignee is null))
                {
                    if (!task.Assignee.Equals(userId))
                    {
                        // When the task is already claimed by another user, throw
                        // exception. Otherwise, ignore
                        // this, post-conditions of method already met.
                        throw new ActivitiTaskAlreadyClaimedException(task.Id, task.Assignee);
                    }
                }
示例#27
0
        protected internal virtual ITaskEntity VerifyTaskParameters(ICommandContext commandContext)
        {
            ITaskEntity task = commandContext.TaskEntityManager.FindById <ITaskEntity>(new KeyValuePair <string, object>("id", taskId));

            if (task == null)
            {
                throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, typeof(ITask));
            }

            if (task.Suspended)
            {
                throw new ActivitiException("It is not allowed to add an attachment to a suspended task");
            }

            return(task);
        }
        public virtual IIdentityLinkEntity AddIdentityLink(ITaskEntity taskEntity, string userId, string groupId, string type)
        {
            IIdentityLinkEntity identityLinkEntity = identityLinkDataManager.Create();

            taskEntity.IdentityLinks.Add(identityLinkEntity);
            identityLinkEntity.Task    = taskEntity;
            identityLinkEntity.UserId  = userId;
            identityLinkEntity.GroupId = groupId;
            identityLinkEntity.Type    = type;
            Insert(identityLinkEntity);
            if (userId is object && taskEntity.ProcessInstanceId is object)
            {
                InvolveUser(taskEntity.ProcessInstance, userId, IdentityLinkType.PARTICIPANT);
            }
            return(identityLinkEntity);
        }
示例#29
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            task.DelegationState = DelegationState.PENDING;
            if (task.Owner is null)
            {
                task.Owner = task.Assignee;
            }
            string userName = null;

            //TODO: 考虑性能问题,暂时不要获取人员信息
            //if (string.IsNullOrWhiteSpace(userId) == false)
            //{
            //    userName = userService.GetUser(userId).GetAwaiter().GetResult()?.FullName;
            //}
            commandContext.TaskEntityManager.ChangeTaskAssignee(task, userId, userName);
            return(null);
        }
示例#30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="task"></param>
        public virtual void RecordTaskAssignment(ITaskEntity task)
        {
            IExecutionEntity executionEntity = task.Execution;

            if (IsHistoryLevelAtLeast(HistoryLevel.ACTIVITY))
            {
                if (executionEntity != null)
                {
                    IHistoricActivityInstanceEntity historicActivityInstance = FindActivityInstance(executionEntity, false, true);
                    if (historicActivityInstance != null)
                    {
                        historicActivityInstance.Assignee     = task.Assignee;
                        historicActivityInstance.AssigneeUser = task.AssigneeUser;
                    }
                }
            }
        }
示例#31
0
 public static void ExecuteAsync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user)
 {
     using (ExecutionContext.SuppressFlow())
         Task.Run(() =>
         {
             try
             {
                 ExecuteSync(task, scheduledTask, user);
             }
             catch (Exception e)
             {
                 e.LogException(ex =>
                 {
                     ex.ControllerName = "SchedulerLogic";
                     ex.ActionName = "ExecuteAsync";
                 });
             }
         });
 }
示例#32
0
 public static void ExecuteAsync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             ExecuteSync(task, scheduledTask, user);
         }
         catch (Exception e)
         {
             e.LogException(ex =>
             {
                 ex.ControllerName = "SchedulerLogic";
                 ex.ActionName = "ExecuteAsync";
             });
         }
     });
 }
示例#33
0
        public static Lite<IEntity> ExecuteSync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user)
        {
            IUserEntity entityIUser = user ?? (IUserEntity)scheduledTask.User.Retrieve();

            using (IsolationEntity.Override(entityIUser.TryIsolation()))
            {
                ScheduledTaskLogEntity stl = new ScheduledTaskLogEntity
                {
                    Task = task,
                    ScheduledTask = scheduledTask,
                    StartTime = TimeZoneManager.Now,
                    MachineName = Environment.MachineName,
                    ApplicationName = Schema.Current.ApplicationName,
                    User = entityIUser.ToLite(),
                };

                using (AuthLogic.Disable())
                {
                    using (Transaction tr = Transaction.ForceNew())
                    {
                        stl.Save();

                        tr.Commit();
                    }
                }

                try
                {
                    using (UserHolder.UserSession(entityIUser))
                    {
                        using (Transaction tr = Transaction.ForceNew())
                        {
                            stl.ProductEntity = ExecuteTask.Invoke(task);

                            using (AuthLogic.Disable())
                            {
                                stl.EndTime = TimeZoneManager.Now;
                                stl.Save();
                            }

                            tr.Commit();
                        }
                    }
                }
                catch (Exception ex)
                {
                    using (AuthLogic.Disable())
                    {
                        if (Transaction.InTestTransaction)
                            throw;

                        var exLog = ex.LogException().ToLite();

                        using (Transaction tr = Transaction.ForceNew())
                        {
                            stl.Exception = exLog;
                            stl.EndTime = TimeZoneManager.Now;
                            stl.Save();

                            tr.Commit();
                        }
                    }
                    throw;

                }

                return stl.ProductEntity;
            }
        }