/// <summary> 根据 <see cref="PartakerEntity.Task"/> 与 <see cref="PartakerEntity.Staff"/> 检查是否<b>不</b>存在相应的 <see cref="PartakerEntity"/>. </summary>
        public static PartakerNotExistsResult CheckStaff(TaskEntity task, Guid staffId)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));

            PartakerEntity partaker = task.Partakers.SingleOrDefault(x => x.Staff.Id == staffId);

            var message =$"{partaker?.Staff.Name}已经是任务成员";

            return Check(partaker, message);
        }
        public void TestSearcher()
        {
            TaskEntity task = new TaskEntity();
            task.Id = 23;

            task.AssignedTo = new UserEntity();
            task.AssignedTo.Id = 34;

            EntityGraphUtilities.PrintEntitiesWithMatchingProperty(task, typeof(UserEntity), "CompanyName", null);
        }
        public void TestSearchByTaskName()
        {
            TaskEntity entity1 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name-1",
                Subject = "Subject"
            };
            TaskEntity entity2 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name-Two",
                Subject = "Subject"
            };
            TaskEntity entity3 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name-Three-3",
                Subject = "Subject"
            };

            TaskDao dao = new TaskDao(SessionFactory);
            dao.Store(entity1);
            dao.Store(entity2);
            dao.Store(entity3);
            QuerableTaskService tasks = new QuerableTaskService(
                new HibernateTaskQueryContext(SessionFactory));

            var t = from task in tasks where task.Name == "Name-1" select task;
            foreach (Task task in t)
            {
                Assert.IsNotNull(task);
            }
            Assert.IsNotNull(t);
            Assert.AreEqual(1, t.Count());
            Task foundTask = t.ElementAt(0);
            Assert.AreEqual("Name-1", foundTask.Name);
            Assert.AreEqual(entity1.TaskId, foundTask.Id);
        }
        public void TestPrinting()
        {
            TaskEntity task = new TaskEntity();
            task.Id = 23;

            task.AssignedTo = new UserEntity();
            task.AssignedTo.Id = 34;

            task.ReplacedBy = task;

            task.Entries.Add(new EntryEntity());

            EntityGraphUtilities.PrintAllEntitiesInGraph(task);
        }
        public static PartakerInvExistsResult CheckPending(IPartakerInvManager partakerInvManager, TaskEntity task, StaffEntity staff)
        {
            if (partakerInvManager == null) throw new ArgumentNullException(nameof(partakerInvManager));
            if (task == null) throw new ArgumentNullException(nameof(task));
            if (staff == null) throw new ArgumentNullException(nameof(staff));

            var pendingInvs = partakerInvManager.FetchPendingPartakerInvs(task.Id, staff.Id); 
            var existed = pendingInvs.FirstOrDefault();

            if (existed == null)
            {
                return new PartakerInvExistsResult(false,"不存在对应的任务邀请.",null);
            }
            return new PartakerInvExistsResult(true, null, existed);
        }
        public static PartakerReqNotExistsResult Check(IPartakerReqManager partakerReqManager, TaskEntity task, StaffEntity staff)
        {
            if (partakerReqManager == null) throw new ArgumentNullException(nameof(partakerReqManager));
            if (task == null) throw new ArgumentNullException(nameof(task));
            if (staff == null) throw new ArgumentNullException(nameof(staff));

            var pendingReqs = partakerReqManager.FetchPendingPartakerReqs(task.Id, staff.Id);
            var existed = pendingReqs.SingleOrDefault();

            if (existed != null)
            {
                return new PartakerReqNotExistsResult(false, "已经存在对应的申请信息.", null);
            }
            return new PartakerReqNotExistsResult(true, null, null);
        }
Example #7
0
        /// <summary>
        /// 改变任务
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="dic"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public string TaskChange(string userCode, Dictionary <string, int> dic, TaskEntity entity)
        {
            IMapper map = DatabaseInstance.Instance();
            string  sql = "";

            if (entity.TaskType == "143")//拣货任务 更改直接更新update就可以了
            {
                foreach (string str in dic.Keys)
                {
                    sql += String.Format("UPDATE tasks t SET t.USER_CODE='{0}' WHERE t.ID={1};", str, entity.TaskID);
                }
            }
            else
            {
                sql = String.Format("delete from tasks where ID={0};", entity.TaskID);
                string sql2 = "INSERT INTO tasks(TASK_TYPE ,BILL_ID ,USER_CODE ,QTY ,CREATE_DATE ,CREATOR ,TASK_DESC ) "
                              + "VALUES(  '{0}'  ,{1} ,'{2}' ,{3}  ,NOW()  ,'{4}'  ,'{5}'   );";
                foreach (string str in dic.Keys)
                {
                    sql += String.Format(sql2, entity.TaskType, entity.BillID, str, dic[str], userCode, entity.TaskDesc);
                }
            }
            string         result = "";
            IDbTransaction trans  = map.BeginTransaction();

            try
            {
                result = map.Execute(sql).ToString();
                trans.Commit();
                result = "Y";
            }
            catch (Exception ex)
            {
                trans.Rollback();
                result = ex.Message;
            }

            return(result);
        }
        public List <Task> Update(TaskEntity taskEntity)
        {
            try
            {
                var parentId = taskEntity.ParentTask == null ? 0 :
                               dbContext.Tasks.FirstOrDefault(x => x.TaskName == taskEntity.ParentTask).TaskId;
                var taskObj = new Task()
                {
                    TaskId    = taskEntity.TaskId,
                    TaskName  = taskEntity.TaskName,
                    ParentId  = parentId,
                    StartDate = taskEntity.StartDate,
                    EndDate   = taskEntity.EndDate,
                    Priority  = taskEntity.Priority,
                    Status    = taskEntity.Status
                };

                dbContext.Entry(taskObj).State = EntityState.Modified;
                var result = dbContext.SaveChanges();
                return((result > 0) ? Get().ToList() : new List <Task>());
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                                                       validationErrors.Entry.Entity.ToString(),
                                                       validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }
        }
        public void CanAddValidTask_ReturnTask()
        {
            // Arrange
            TaskEntity taskEntity = new TaskEntity
            {
                Id           = "Guid1",
                Completeness = false,
                DateTime     = DateTime.Now,
                Description  = "Description",
                Name         = "Name",
            };
            ITaskRepository taskRepository = new TaskRepository();


            // Act
            var result = taskRepository.AddTask(taskEntity);

            // Assert
            Assert.AreEqual(taskEntity, result);

            taskRepository.DeleteTaskById(taskEntity.Id);
        }
        public virtual UserOperationLogContextEntryBuilder InContextOf(TaskEntity task,
                                                                       IList <PropertyChange> propertyChanges)
        {
            if (propertyChanges == null || propertyChanges.Count == 0)
            {
                if (UserOperationLogEntryFields.OperationTypeCreate.Equals(EntryRenamed.OperationType))
                {
                    propertyChanges = new List <PropertyChange>()
                    {
                        PropertyChange.EmptyChange
                    };;
                }
            }
            EntryRenamed.PropertyChanges = propertyChanges;

            IResourceDefinitionEntity definition = task.ProcessDefinition;

            if (definition != null)
            {
                EntryRenamed.ProcessDefinitionKey = definition.Key;
                EntryRenamed.DeploymentId         = definition.DeploymentId;
            }
            else if (!ReferenceEquals(task.CaseDefinitionId, null))
            {
                throw new NotImplementedException();
                //definition = task.CaseDefinition;
                EntryRenamed.DeploymentId = definition.DeploymentId;
            }

            EntryRenamed.ProcessDefinitionId = task.ProcessDefinitionId;
            EntryRenamed.ProcessInstanceId   = task.ProcessInstanceId;
            EntryRenamed.ExecutionId         = task.ExecutionId;
            EntryRenamed.CaseDefinitionId    = task.CaseDefinitionId;
            EntryRenamed.CaseInstanceId      = task.CaseInstanceId;
            EntryRenamed.CaseExecutionId     = task.CaseExecutionId;
            EntryRenamed.TaskId = task.Id;

            return(this);
        }
Example #11
0
        /// <summary>
        /// Convert task model into the task entity.
        /// </summary>
        /// <param name="taskModel">The <see cref="TaskModel"/> instance.</param>
        /// <returns>The <see cref="TaskEntity"/> instance.</returns>
        public TaskEntity Convert(TaskModel taskModel)
        {
            logger.WriteTrace("Converting {0} into the TaskEntity...", taskModel);

            string[] args = expressionConverter.SerializeArguments(taskModel.ActivationData.Arguments);

            TaskEntity entity = new TaskEntity
            {
                Id               = taskModel.Id,
                QueueId          = taskModel.QueueId,
                InstanceType     = jsonConverter.ConvertToJson(taskModel.ActivationData.InstanceType),
                Method           = taskModel.ActivationData.Method.Name,
                ParametersTypes  = jsonConverter.ConvertToJson(taskModel.ActivationData.ArgumentTypes),
                Arguments        = jsonConverter.ConvertToJson(args),
                TaskState        = taskModel.TaskState,
                RepeatCrashCount = taskModel.ScheduleInformation.RepeatCrashCount
            };

            logger.WriteTrace("Converting {0} into the TaskEntity has been successfully completed. Result = {1}", taskModel, entity);

            return(entity);
        }
        public async Task <IResultModel> Add(TaskEntity model)
        {
            model.Id = Guid.NewGuid();

            if (_repository.Exists(m => m.Group == model.Group && m.TaskCode == model.TaskCode))
            {
                return(ResultModel.Failed($"当前任务组{model.Group}已存在任务编码${model.TaskCode}"));
            }
            model.Status  = JobStatus.Stop;
            model.EndDate = model.EndDate.AddDays(1);

            int i = await _repository.InsertAsync(model);

            if (i > 0)
            {
                return(ResultModel.Success());
            }
            else
            {
                return(ResultModel.Failed());
            }
        }
Example #13
0
        protected internal virtual void checkTaskPermission(TaskEntity task, Permission processDefinitionPermission, Permission taskPermission)
        {
            string taskId      = task.Id;
            string executionId = task.ExecutionId;

            if (!string.ReferenceEquals(executionId, null))
            {
                // if task exists in context of a process instance
                // then check the following permissions:
                // - 'taskPermission' on TASK
                // - 'processDefinitionPermission' on PROCESS_DEFINITION

                ExecutionEntity         execution         = task.getExecution();
                ProcessDefinitionEntity processDefinition = execution.getProcessDefinition();

                CompositePermissionCheck readTaskPermission = (new PermissionCheckBuilder()).disjunctive().atomicCheckForResourceId(TASK, taskId, taskPermission).atomicCheckForResourceId(PROCESS_DEFINITION, processDefinition.Key, processDefinitionPermission).build();

                AuthorizationManager.checkAuthorization(readTaskPermission);
            }
            else
            {
                // if task does not exist in context of process
                // instance, then it is either a (a) standalone task
                // or (b) it exists in context of a case instance.

                // (a) standalone task: check following permission
                // - 'taskPermission' on TASK
                // (b) task in context of a case instance, in this
                // case it is not necessary to check any permission,
                // because such tasks can always be read

                string caseExecutionId = task.CaseExecutionId;
                if (string.ReferenceEquals(caseExecutionId, null))
                {
                    AuthorizationManager.checkAuthorization(taskPermission, TASK, taskId);
                }
            }
        }
        /// <summary>
        ///     根据流程实际进度做界面显示(去除Step值判断)
        /// </summary>
        private void InitStepOn()
        {
            List <TaskEntity> list    = EDoc2ProcessManager.GetTaskData(IncidentId);
            TaskEntity        endItem = list.FirstOrDefault(i => i.Status == "已完成" && i.StepName == "结束");

            if (endItem != null)
            {
                Page.Title = FaProcessSteppService.GetStepText(FaProcessStepEnum.Complete);
                Step2.AddCssClass("on");
                return;
            }
            TaskEntity cItem = list.FirstOrDefault(i => i.Status == "激活");

            if (cItem != null)
            {
                FaProcessStepEnum stepEnum = FaProcessSteppService.GetStepVal(cItem.StepName);
                switch (stepEnum)
                {
                case FaProcessStepEnum.Start:
                    Step0.AddCssClass("on");
                    break;

                case FaProcessStepEnum.FaDirector:
                    Step1.AddCssClass("on");
                    break;

                case FaProcessStepEnum.Complete:
                    Step2.AddCssClass("on");
                    break;
                }
                Page.Title = FaProcessSteppService.GetStepText(stepEnum);
            }
            else
            {
                Page.Title = FaProcessSteppService.GetStepText(FaProcessStepEnum.Start);
                Step0.AddCssClass("on");
            }
        }
        public void TestCreateUpdateTask()
        {
            TaskEntity entity = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name",
                Subject = "Subject"
            };

            Task task = new Task(entity)
                            {
                                LoggingService = new Mock<ILoggingService>().Object,
                                Priority = Priority.High

                            };

            TaskDao dao=new TaskDao(SessionFactory);
            task.Accept(dao);
            //update priority
            task.Priority = Priority.Medium;
            task.Name = "New Name";
            task.Subject = "New Subject";
            task.Accept(dao);
            task.AddComment("Bad comment");
            task.AddComment("Good comment");
            task.Accept(dao);
            TrickVisitor visitor=new TrickVisitor
                                     {
                                         OnEntityVisit = e=>e.Version=1
                                     };
            task.Accept(visitor);
            task.Name = "123";
            task.Accept(dao);
        }
Example #16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings({ "rawtypes", "unchecked" }) protected void initializeTaskCandidateUsers(org.camunda.bpm.engine.impl.persistence.entity.TaskEntity task, org.camunda.bpm.engine.delegate.VariableScope variableScope)
        protected internal virtual void initializeTaskCandidateUsers(TaskEntity task, VariableScope variableScope)
        {
            ISet <Expression> candidateUserIdExpressions = taskDefinition.CandidateUserIdExpressions;

            foreach (Expression userIdExpr in candidateUserIdExpressions)
            {
                object value = userIdExpr.getValue(variableScope);

                if (value is string)
                {
                    IList <string> candiates = extractCandidates((string)value);
                    task.addCandidateUsers(candiates);
                }
                else if (value is System.Collections.ICollection)
                {
                    task.addCandidateUsers((System.Collections.ICollection)value);
                }
                else
                {
                    throw new ProcessEngineException("Expression did not resolve to a string or collection of strings");
                }
            }
        }
Example #17
0
        public void Add_Task()
        {
            var taskId = _tasks.Count() + 1;
            var task   = new TaskEntity
            {
                TaskId     = taskId,
                TaskName   = "Coding",
                ParentId   = 1,
                ParentName = "Project Task",
                Priority   = 2,
                ActiveInd  = "Y",
                StartDate  = new DateTime(2018, 04, 21),
                EndDate    = new DateTime(2018, 08, 26)
            };

            _mockRepository.AddTask(task);
            Assert.IsTrue(_tasks.Count() == 4);
            TaskEntity testTask = _mockRepository.GetTaskById(taskId);

            Assert.IsNotNull(testTask);
            Assert.AreSame(testTask.GetType(), typeof(TaskEntity));
            Assert.AreEqual(taskId, testTask.TaskId);
        }
        public async Task <IActionResult> PostTaskEntity(TaskEntity taskEntity)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                _taskRunner.ExecuteTask(taskEntity);
                var taskDto = _mapper.MapTo(taskEntity);

                taskEntity.RegistrationDate = DateTime.UtcNow;
                _context.TaskEntities.Add(taskEntity);
                await _context.SaveChangesAsync();

                return(CreatedAtAction("GetTaskEntity", new { id = taskDto.TaskId }, taskDto));
            }
            catch (Exception)
            {
                throw new BusinessException(ExceptionMessages.ExceptionOnCreateTask);
            }
        }
Example #19
0
        public void Update_Task()
        {
            var taskId = 3;
            var task   = new TaskEntity
            {
                TaskId    = taskId,
                TaskName  = "Task Update",
                ParentId  = 1,
                Priority  = 10,
                StartDate = "11/01/2018",
                EndDate   = "11/15/2018",
                ProjectId = 1,
                UserId    = 1234571,
            };

            _mockRepository.UpdateTask(task);

            var updatedProject = _mockRepository.GetTaskById(taskId);

            Assert.IsTrue(updatedProject.TaskName == "Task Update");
            Assert.IsTrue(updatedProject.Priority == 10);
            Assert.IsTrue(updatedProject.UserId == 1234571);
        }
        public IActionResult Post([FromBody] CreateTask model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            TaskEntity task = mapper.Map <TaskEntity>(model);

            if (task == null)
            {
                return(BadRequest());
            }

            TaskCard card = db.Cards.Create(task);

            if (card == null)
            {
                return(BadRequest());
            }

            return(Ok(card));
        }
        public void Update_Task()
        {
            var taskId = 3;
            var task   = new TaskEntity
            {
                TaskId    = taskId,
                TaskName  = "Test Task",
                ParentId  = 1,
                Priority  = 12,
                StartDate = "05/01/2019",
                EndDate   = "30/01/2018",
                ProjectId = 1,
                UserId    = 6565985,
            };

            _mockRepository.UpdateTask(task);

            var updatedProject = _mockRepository.GetTaskById(taskId);

            Assert.IsTrue(updatedProject.TaskName == "Test Task");
            Assert.IsTrue(updatedProject.Priority == 12);
            Assert.IsTrue(updatedProject.UserId == 6565985);
        }
Example #22
0
        public virtual void logVariableOperation(string operation, string executionId, string taskId, PropertyChange propertyChange)
        {
            if (UserOperationLogEnabled)
            {
                UserOperationLogContext context = new UserOperationLogContext();

                UserOperationLogContextEntryBuilder entryBuilder = UserOperationLogContextEntryBuilder.entry(operation, EntityTypes.VARIABLE).propertyChanges(propertyChange);

                if (!string.ReferenceEquals(executionId, null))
                {
                    ExecutionEntity execution = ProcessInstanceManager.findExecutionById(executionId);
                    entryBuilder.inContextOf(execution).category(org.camunda.bpm.engine.history.UserOperationLogEntry_Fields.CATEGORY_OPERATOR);
                }
                else if (!string.ReferenceEquals(taskId, null))
                {
                    TaskEntity task = TaskManager.findTaskById(taskId);
                    entryBuilder.inContextOf(task, Arrays.asList(propertyChange)).category(org.camunda.bpm.engine.history.UserOperationLogEntry_Fields.CATEGORY_TASK_WORKER);
                }

                context.addEntry(entryBuilder.create());
                fireUserOperationLog(context);
            }
        }
        public void CanGetTasksByName()
        {
            // Arrange
            TaskEntity taskEntity = new TaskEntity
            {
                Id           = "Guid1",
                Completeness = false,
                DateTime     = DateTime.Now,
                Description  = "Description",
                Name         = "Name",
            };
            ITaskRepository taskRepository = new TaskRepository();

            taskRepository.AddTask(taskEntity);

            // Act
            var result = taskRepository.GetTasksByName(taskEntity.Name);

            // Assert
            Assert.AreEqual(taskEntity, result.FirstOrDefault(t => t.Name == taskEntity.Name));

            taskRepository.DeleteTaskById(taskEntity.Id);
        }
Example #24
0
        public void Should_create_zip_file()
        {
            //Arrange
            _mockTaskRepository = MockRepository.GenerateStub <ITaskRepository>();
            var task = new TaskEntity()
            {
                Status       = "done",
                DownloadPath = _testDirectoryPath
            };

            _mockTaskRepository.Stub(t => t.GetTaskById(1)).Return(task);
            _mockTaskRepository.Stub(t => t.UpdateTask(task));
            ZipProvider zp = new ZipProvider(_mockTaskRepository);

            //Act
            zp.Zip(_testDirectoryPath, 1);

            //Assert
            _mockTaskRepository.AssertWasCalled(t => t.GetTaskById(1));
            _mockTaskRepository.AssertWasCalled(t => t.UpdateTask(task));
            fi = new FileInfo(Path.Combine(Path.GetTempPath(), "Test.zip"));
            Assert.AreEqual(fi.Exists, true);
        }
Example #25
0
        protected internal virtual void InitializeTaskCandidateUsers(TaskEntity task, IVariableScope variableScope)
        {
            var candidateUserIdExpressions = taskDefinition.CandidateUserIdExpressions;

            foreach (var userIdExpr in candidateUserIdExpressions)
            {
                var value = userIdExpr.GetValue(variableScope);

                if (value is string)
                {
                    var candiates = ExtractCandidates((string)value);
                    task.AddCandidateUsers(candiates);
                }
                else if (value is ICollection)
                {
                    task.AddCandidateUsers(((ICollection <string>)value).Distinct().ToArray());
                }
                else
                {
                    throw new ProcessEngineException("Expression did not resolve to a string or collection of strings");
                }
            }
        }
Example #26
0
        public void CreateDefaultData()
        {
            _tasks = new List<TaskEntity>();
            _buckets = new BucketSet<TaskEntity>("FirstEntryDate", BucketLumpType.IncludeItemsLessThanComparison);

            Random rng = new Random();

            for (int i = 0; i < 100; i++)
            {
                TaskEntity task = new TaskEntity();

                task.FirstEntryDate = DateTime.Now.AddDays(rng.Next(-365, 365));

                _tasks.Add(task);
            }

            _testTime = DateTime.Now;

            _buckets.AddRemainderBucket();
            _buckets.AddBucket(_testTime);
            _buckets.AddBucket(_testTime.AddDays(100));
            _buckets.AddBucket(_testTime.AddDays(200));
        }
        public void SortTasksByCategory_CanSortByCategoryTitle_ReturnTasks()
        {
            // Arrange
            var category = new TaskCategoryEntity()
            {
                Id       = "Guid 1",
                DateTime = DateTime.Now,
                Title    = "Daily",
            };

            var taskEntity = new TaskEntity
            {
                Id           = "Guid1",
                Completeness = false,
                DateTime     = DateTime.Now,
                Description  = "Description",
                Name         = "Name",
                Category     = category,
            };

            ITaskRepository         taskRepository         = new TaskRepository();
            ITaskCategoryRepository taskCategoryRepository = new TaskCategoryRepository();

            taskRepository.AddTask(taskEntity);


            // Act
            var result = taskRepository.SortTasksByCategory(taskEntity.Category.Title);

            // Assert
            Assert.IsNotNull(result);

            Assert.AreEqual(taskEntity, result.FirstOrDefault(t => t.Name == taskEntity.Name));

            taskRepository.DeleteTaskById(taskEntity.Id);
            taskCategoryRepository.DeleteCategoryById(category.Id);
        }
Example #28
0
        public virtual object Execute(CommandContext commandContext)
        {
            EnsureUtil.EnsureNotNull("taskId", TaskId);

            ITaskManager taskManager = commandContext.TaskManager;
            TaskEntity   task        = taskManager.FindTaskById(TaskId);

            EnsureUtil.EnsureNotNull("Cannot find ITask with id " + TaskId, "ITask", task);

            CheckClaimTask(task, commandContext);

            if (!ReferenceEquals(UserId, null))
            {
                if (!ReferenceEquals(task.Assignee, null))
                {
                    if (!task.Assignee.Equals(UserId))
                    {
                        // When the ITask is already claimed by another user, throw exception. Otherwise, ignore
                        // this, post-conditions of method already met.
                        throw new TaskAlreadyClaimedException(task.Id, task.Assignee);
                    }
                }
                else
                {
                    task.Assignee = UserId;
                }
            }
            else
            {
                // ITask should be assigned to no one
                task.Assignee = null;
            }

            task.CreateHistoricTaskDetails(UserOperationLogEntryFields.OperationTypeClaim);

            return(null);
        }
        public void CanUpdateValidTask_ReturnTask()
        {
            // Arrange
            var taskEntity = new TaskEntity
            {
                Id           = Guid.NewGuid().ToString(),
                Completeness = false,
                DateTime     = DateTime.Now,
                Description  = "Description",
                Name         = "Name",
            };

            var taskEntityUPDATE = new TaskEntity
            {
                Id           = taskEntity.Id,
                Completeness = true,
                DateTime     = DateTime.Now,
                Description  = "Description 2",
                Name         = "Name 2",
            };

            ITaskRepository taskRepository = new TaskRepository();

            taskRepository.AddTask(taskEntity);

            // Act
            var result = taskRepository.UpdateTask(taskEntityUPDATE);

            taskRepository.DeleteTaskById(taskEntityUPDATE.Id);

            // Assert
            Assert.AreEqual(taskEntity, result);
            Assert.AreEqual(taskEntityUPDATE.Name, result.Name);
            Assert.AreEqual(taskEntityUPDATE.Description, result.Description);
            Assert.AreEqual(taskEntityUPDATE.DateTime, result.DateTime);
            Assert.AreEqual(taskEntityUPDATE.Id, result.Id);
        }
Example #30
0
        /// <summary>
        /// 新建 1成功 0失败 2存在TaskName
        /// </summary>
        /// <param name="taskEntity"></param>
        /// <returns></returns>
        public int Insert(TaskEntity taskEntity)
        {
            var sql       = @"INSERT INTO T8_Task (TaskID,TaskName,Cron,DataHandler,DBConnectString_Hashed,SQL,DataType,IsDelete,TaskStatus,CreateTime,ModifyTime,RecentRunTime,NextFireTime,Remark,Enabled,CycleType) 
                       VALUES(@TaskID,@TaskName,@Cron,@DataHandler,@DBConnectString_Hashed,@SQL,@DataType,@IsDelete,@TaskStatus,@CreateTime,@ModifyTime,@RecentRunTime,@NextFireTime,@Remark,@Enabled,@CycleType)";
            var existsSql = "SELECT COUNT(*) AS Cnt FROM T8_Task WHERE TaskName=@TaskName";

            return(base.ExecuteFor((conn) =>
            {
                var prms = new
                {
                    TaskID = taskEntity.TaskID,
                    TaskName = taskEntity.TaskName,
                    Cron = taskEntity.Cron,
                    DataHandler = taskEntity.DataHandler,
                    DBConnectString_Hashed = taskEntity.DBConnectString_Hashed,
                    SQL = taskEntity.SQL,
                    DataType = taskEntity.DataType,
                    IsDelete = taskEntity.IsDelete,
                    TaskStatus = taskEntity.TaskStatus,
                    CreateTime = taskEntity.CreateTime != DateTime.MinValue ? taskEntity.CreateTime.ToString("s") : DateTime.Now.ToString("s"),
                    ModifyTime = taskEntity.ModifyTime != DateTime.MinValue ? taskEntity.ModifyTime.ToString("s") : null,
                    RecentRunTime = taskEntity.RecentRunTime != DateTime.MinValue ? taskEntity.RecentRunTime.ToString("s") : null,
                    NextFireTime = taskEntity.NextFireTime != DateTime.MinValue ? taskEntity.NextFireTime.ToString("s") : null,
                    Remark = taskEntity.Remark,
                    Enabled = taskEntity.Enabled != 0 ? taskEntity.Enabled : 1,
                    CycleType = taskEntity.CycleType
                };

                var cnt = conn.QueryDT(existsSql, prms).Rows[0]["Cnt"].ToString().ToInt();
                if (cnt > 0)
                {
                    return 2;
                }
                int result = conn.Execute(sql, prms);
                return result > 0 ? 1 : 0;
            }));
        }
        public async Task <CheckTaskIntersectResponse> Handle(CheckTaskIntersectRequest request, CancellationToken cancellationToken)
        {
            var tempTask = new TaskEntity()
            {
                PlanStart = request.StartUtc.UnixTimeStampToDateTime(),
                PlanEnd   = request.EndUtc.UnixTimeStampToDateTime(),
                LoaderId  = request.LoaderId,
                Id        = 0
            };

            IEnumerable <TaskEntity> taskWithSameLoaderAndDate = await _taskRepository
                                                                 .GetTasksWithSameDateAndLoader(request.LoaderId, request.StartUtc.UnixTimeStampToDateTime(), null)
                                                                 .ToListAsync(cancellationToken);


            var intersectedTask = taskWithSameLoaderAndDate
                                  .FirstOrDefault(t => t.Type == request.TaskType && t.IsIntersect(tempTask));

            if (intersectedTask != null)
            {
                _logger.LogInformation(@$ "Задание для данного погрузчика на это время уже существует.
Новое задание:
    Время задания: {tempTask.PlanStart:dd.MM.yyyy HH:mm:ss}
    ИД погрузчика: {request.LoaderId}
    Тип задания: {request.TaskType.GetDescription()}
Существующее задание:
    Время задания: {intersectedTask.PlanStart:dd.MM.yyyy HH:mm:ss}
    ИД погрузчика: {intersectedTask.LoaderId}
    Тип задания: {intersectedTask.Type.GetDescription()}");
            }
            var result = new CheckTaskIntersectResponse()
            {
                TaskIntersected = intersectedTask != null
            };

            return(result);
        }
Example #32
0
        public virtual Void execute(CommandContext commandContext)
        {
            ensureNotNull("taskId", taskId);

            TaskManager taskManager = commandContext.TaskManager;
            TaskEntity  task        = taskManager.findTaskById(taskId);

            ensureNotNull("Cannot find task with id " + taskId, "task", task);

            checkClaimTask(task, commandContext);

            if (!string.ReferenceEquals(userId, null))
            {
                if (!string.ReferenceEquals(task.Assignee, 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 TaskAlreadyClaimedException(task.Id, task.Assignee);
                    }
                }
                else
                {
                    task.Assignee = userId;
                }
            }
            else
            {
                // Task should be assigned to no one
                task.Assignee = null;
            }

            task.createHistoricTaskDetails(org.camunda.bpm.engine.history.UserOperationLogEntry_Fields.OPERATION_TYPE_CLAIM);

            return(null);
        }
Example #33
0
        /// <summary>
        /// Creates a model based on the given domain entity.
        /// </summary>
        /// <param name="entity">The domain entity.</param>
        /// <param name="serializer">The JSON serializer.</param>
        /// <returns>The domain entity as a model.</returns>
        public static TaskModel Create(TaskEntity entity, IDefaultJsonSerializer serializer)
        {
            if (entity == null)
            {
                return(null);
            }

            var model = new TaskModel
            {
                Id           = entity.Id.ToString(),
                CreatedDate  = entity.CreatedDate,
                ModifiedDate = entity.ModifiedDate,
                QueuedDate   = entity.QueuedDate,
                StartedDate  = entity.StartedDate,
                EndedDate    = entity.EndedDate,
                Status       = Enum.TryParse(entity.Status.ToString(), out TaskStatus status) ? status : TaskStatus.Created,
                Message      = entity.Message,
                Position     = entity.Position,
                Progress     = entity.Progress,
                UserId       = entity.UserId
            };

            if (Enum.TryParse(entity.CommandType.ToString(), out CommandType commandType))
            {
                switch (commandType)
                {
                case CommandType.ProcessObjectCommand:
                    model.Command = serializer.Deserialize <ProcessObjectCommand>(entity.CommandSerialized);
                    break;

                default:
                    break;
                }
            }

            return(model);
        }
Example #34
0
        /// <summary>
        /// 编辑
        /// </summary>
        private void ShowEditZone()
        {
            TaskEntity editEntity = SelectedTaskRow;

            if (editEntity == null)
            {
                MsgBox.Warn("没有要修改的数据。");
                return;
            }

            if (editEntity.TaskType != "143")
            {
                MsgBox.Warn("先阶段只允许更改拣货任务,其他功能后续更新。");
                return;
            }
            #region
            //List<TaskEntity> list = new List<TaskEntity>();
            //foreach(TaskEntity entity in bindingSource1.DataSource as List<TaskEntity>)
            //{
            //    if(editEntity.UserCode==entity.UserCode)
            //    {
            //        list.Add(entity);
            //    }
            //}
            #endregion
            string resultMsg = this.taskDal.TaskState(editEntity.TaskType, editEntity.TaskID);
            if (resultMsg != "Y")
            {
                MsgBox.Warn(resultMsg);
                return;
            }
            FrmTaskChange frm = new FrmTaskChange(editEntity.TaskType, editEntity);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadDataAndBindGrid();
            }
        }
Example #35
0
        public async Task <TaskModel> Assign(AuthorizedDto <AssignTaskDto> dto)
        {
            return(await Execute(async() => {
                using (UnitOfWork db = new UnitOfWork())
                {
                    IRepo <AccountEntity> accountRepo = db.GetRepo <AccountEntity>();

                    TaskEntity task = await db.GetRepo <TaskEntity>().Get(dto.Data.Id.Value);

                    if (task.creator_account_id != dto.Session.UserId)
                    {
                        throw new NotPermittedException($"Creator of task #{task.id}");
                    }

                    AccountEntity initiator = await accountRepo.Get(dto.Session.UserId);
                    AccountEntity assignee = dto.Data.AssigneeAccountId.HasValue ? await accountRepo.Get(dto.Data.AssigneeAccountId.Value) : null;
                    AccountEntity reviewer = dto.Data.ReviewerAccountId.HasValue ? await accountRepo.Get(dto.Data.ReviewerAccountId.Value) : null;

                    if (assignee != null && !assignee.Bosses.Contains(initiator) && assignee != initiator)
                    {
                        throw new NotPermittedException($"Boss for assignee Account #{assignee.id}");
                    }

                    if (reviewer != null && !reviewer.Bosses.Contains(initiator) && reviewer != initiator)
                    {
                        throw new NotPermittedException($"Boss for reviewer Account #{reviewer.id}");
                    }

                    task.assignee_account_id = assignee?.id;
                    task.reviewer_account_id = reviewer?.id;

                    await db.Save();

                    return task.ToModel <TaskModel>();
                }
            }));
        }
Example #36
0
        public void ChangeTaskStatus_Completes_A_Task()
        {
            var taskId = 103;
            var userId = "203";
            var task   = new TaskEntity()
            {
                TaskId      = taskId,
                UserId      = userId,
                IsComplete  = false,
                Description = "description",
                LastUpdated = DateTime.Now,
            };
            var now = new DateTime(2019, 5, 17, 13, 24, 9);
            var dateTimeProvider = _mockFactory.Create <IDateTimeProvider>();

            dateTimeProvider.Setup(d => d.GetCurrentTime()).Returns(now);

            var repository = _mockFactory.Create <ITaskRepository>();

            repository.Setup(r => r.GetTask(It.Is <int>(i => i == taskId), It.Is <string>(s => s == userId))).Returns(task);
            repository.Setup(r => r.SaveTask(It.Is <TaskEntity>(
                                                 t => t.TaskId == taskId &&
                                                 t.UserId == userId &&
                                                 t.IsComplete &&
                                                 t.Description == "description" &&
                                                 t.LastUpdated == now
                                                 ))).Returns(true);

            var target = new TaskManager(repository.Object, dateTimeProvider.Object);
            var result = target.ChangeTaskStatus(userId, taskId, true);


            Assert.IsTrue(result);

            dateTimeProvider.VerifyAll();
            repository.VerifyAll();
        }
        // Test update task functionality
        public void ShouldUpdateTask()
        {
            var taskId     = 3;
            var taskDetail = new TaskEntity
            {
                TaskId       = taskId,
                Task         = "Update Repository Creation", //"Repository Creation",
                ParentId     = 2,                            //1
                TaskPriority = 3,                            //2
                TaskStatus   = "Y",
                StartDate    = new DateTime(2018, 9, 10),    //DateTime(2018, 9, 9),
                EndDate      = new DateTime(2018, 10, 9)     //DateTime(2018, 9, 9)
            };

            _mockRepository.UpdateTask(taskDetail);

            var UpdatedTask = _mockRepository.GetTask(taskId);

            Assert.IsTrue(UpdatedTask.Task == "Update Repository Creation");
            Assert.IsTrue(UpdatedTask.ParentId == 2);
            Assert.IsTrue(UpdatedTask.TaskPriority == 3);
            Assert.IsTrue(UpdatedTask.StartDate == new DateTime(2018, 9, 10));
            Assert.IsTrue(UpdatedTask.EndDate == new DateTime(2018, 10, 9));
        }
Example #38
0
        public virtual object execute(CommandContext commandContext)
        {
            AttachmentEntity attachment = (AttachmentEntity)commandContext.AttachmentManager.findAttachmentByTaskIdAndAttachmentId(taskId, attachmentId);

            ensureNotNull("No attachment exist for task id '" + taskId + " and attachmentId '" + attachmentId + "'.", "attachment", attachment);

            commandContext.DbEntityManager.delete(attachment);

            if (!string.ReferenceEquals(attachment.ContentId, null))
            {
                commandContext.ByteArrayManager.deleteByteArrayById(attachment.ContentId);
            }

            if (!string.ReferenceEquals(attachment.TaskId, null))
            {
                TaskEntity task = commandContext.TaskManager.findTaskById(attachment.TaskId);

                PropertyChange propertyChange = new PropertyChange("name", null, attachment.Name);

                commandContext.OperationLogManager.logAttachmentOperation(org.camunda.bpm.engine.history.UserOperationLogEntry_Fields.OPERATION_TYPE_DELETE_ATTACHMENT, task, propertyChange);
            }

            return(null);
        }
Example #39
0
 public TaskExistsResult(bool isSucceed, String message, TaskEntity task)
     : base(isSucceed, message)
 {
     this.Task = task;
 }
Example #40
0
 private TaskEntity CreateNewTask(int taskIndex, StaffEntity staff)
 {
     TaskEntity task = new TaskEntity();
     task.Id = Guid.NewGuid();
     task.Name = "Task-" + taskIndex;
     task.Creator = staff;
     task.Level = 3;
     task.Goal = task.Name;
     return task;
 }
Example #41
0
    public bool AddTask(TaskEntity entity)
    {
        try
        {
            string sql = @"insert into task(TypeID,CompleteTime,Title,Content,userid,createTime,Attachment,FileName,ProcessID)
                            values(@TypeID,@CompleteTime,@Title,@Content,@userid,@createTime,@Attachment,@FileName,@ProcessID)";

            SqlParameter[] par = new SqlParameter[9];
            par[0] = new SqlParameter("@TypeID", entity.TypeID);
            if (entity.Status == "Completed")
            {
                par[1] = new SqlParameter("@CompleteTime", DateTime.Now);
            }
            else
            {
                par[1] = new SqlParameter("@CompleteTime", DBNull.Value);
            }
            par[2] = new SqlParameter("@Title", entity.Title);
            par[3] = new SqlParameter("@Content", entity.Content);
            par[4] = new SqlParameter("@userid", entity.UserID);
            par[5] = new SqlParameter("@createTime", entity.CreateTime);
            par[6] = new SqlParameter("@Attachment", entity.Attachment);
            par[7] = new SqlParameter("@FileName", entity.FileName);
            par[8] = new SqlParameter("@ProcessID", entity.ProcessID);
            int result = SqlHelper.ExecuteSql(sql, par);
            return result > 0;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Example #42
0
        //[DataScoped(true)]
        public void ChangeTaskName(Guid taskId, string newName)
        {
            if (string.IsNullOrEmpty(newName))
                throw new ArgumentException("任务名称不可为空.", nameof(newName));

            Args.MaxLength(newName, 64, nameof(newName), "任务名称");
            using (var tx = TxManager.Acquire())
            {
                var task = TaskExistsResult.Check(m_TaskManager, taskId).ThrowIfFailed().Task;
                var partaker = AccountIsPartakerResult.Check(task, this.AccountId).ThrowIfFailed().Partaker;
                TaskNotExistsResult.CheckInOrg(this.m_TaskManager, task.Creator.Org.Id, newName, taskId).ThrowIfFailed();

                var originalTask = new TaskEntity()
                {
                    Id = task.Id,
                    Name = task.Name,
                    ConversationId = task.ConversationId
                };
                task.Name = newName;
                //更新数据库
                m_TaskManager.UpdateTask(task);

                tx.Complete();


                Task.Factory.StartNew(async () =>
                {
                    //更新聊天室名称 
                    await m_IMService.ChangeTaskName(partaker.Staff.Id.ToString(), originalTask, newName);

                    //发送群消息
                    var message = string.Format(m_Config["LeanCloud:Messages:Task:ChangeTaskName"], partaker.Staff.Name,
                        newName);
                    await
                        m_IMService.SendTextMessageByConversationAsync(task.Id, partaker.Staff.Account.Id, task.ConversationId, task.Name, message);
                    m_TaskLogManager.CreateTaskLog(task.Id, partaker.Staff.Id, task.GetType().FullName, task.Id,
                        ActionKinds.UpdateColumn, $"修改任务名称为{newName}","Name");
                });
            }

        }
        public void TestSearchSimpleAndOr()
        {
            TaskEntity entity1 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Failed,
                Created = DateTime.UtcNow,
                Name = "Name-1",
                Subject = "Subject"
            };
            TaskEntity entity2 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.High,
                Status = TaskStatus.Ready,
                Created = DateTime.UtcNow,
                Name = "Name-Two",
                Subject = "Subject"
            };
            TaskEntity entity3 = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.InProgress,
                Created = DateTime.UtcNow,
                Name = "Name-Three-3",
                Subject = "Subject"
            };

            TaskDao dao = new TaskDao(SessionFactory);
            dao.Store(entity1);
            dao.Store(entity2);
            dao.Store(entity3);
            QuerableTaskService tasks = new QuerableTaskService(
                new HibernateTaskQueryContext(SessionFactory));

            var t = from task in tasks
                    where task.Name.StartsWith("Name")
                        && task.Priority > Priority.Normal
                        || task.Status==TaskStatus.InProgress
                    select task;

            Assert.IsNotNull(t);
            foreach (Task task in t)
            {
                Assert.IsNotNull(task);
            }
            Assert.AreEqual(2, t.Count());
            Task foundTask = t.ElementAt(0);
            Assert.AreEqual("Name-Two", foundTask.Name);
            Assert.AreEqual(entity2.TaskId, foundTask.Id);
            foundTask = t.ElementAt(1);
            Assert.AreEqual("Name-Three-3", foundTask.Name);
            Assert.AreEqual(entity3.TaskId, foundTask.Id);
        }
 public void TestStoreTaskEntity()
 {
     TaskEntity entity=new TaskEntity
                           {
                               TaskId = new TaskId(),
                               Initiator = new IdentityId().GetIdentity(),
                               Priority = Priority.Normal,
                               Status = TaskStatus.Created,
                               Created = DateTime.UtcNow,
                               Name="Name",
                               Subject="Subject"
                           };
     ISession session = SessionFactory.OpenSession();
     session.Save(entity);
     session.Flush();
 }
 public void TestSearchCollectionContains()
 {
     Guid userGuid1 = Guid.NewGuid();
     Guid userGuid2 = Guid.NewGuid();
     TaskEntity entity1 = new TaskEntity
     {
         TaskId = new TaskId(),
         Initiator = new IdentityId().GetIdentity(),
         Priority = Priority.Normal,
         Status = TaskStatus.Failed,
         Created = DateTime.UtcNow,
         Name = "Name-1",
         Subject = "Subject"
     };
     TaskEntity entity2 = new TaskEntity
     {
         TaskId = new TaskId(),
         Initiator = new IdentityId().GetIdentity(),
         Priority = Priority.High,
         Status = TaskStatus.Ready,
         Created = DateTime.UtcNow,
         Name = "Name-Two",
         Subject = "Subject"
     };
     TaskEntity entity3 = new TaskEntity
     {
         TaskId = new TaskId(),
         Initiator = new IdentityId().GetIdentity(),
         Priority = Priority.Normal,
         Status = TaskStatus.InProgress,
         Created = DateTime.UtcNow,
         Name = "Name-Three-3",
         Subject = "Subject"
     };
     entity2.PotentialOwners.Add(new IdentityId(userGuid1).GetIdentity());
     entity2.PotentialOwners.Add(new IdentityId(userGuid2).GetIdentity());
     entity1.BusinessAdministrators.Add(new IdentityId(userGuid1).GetIdentity());
     TaskDao dao = new TaskDao(SessionFactory);
     dao.Store(entity1);
     dao.Store(entity2);
     dao.Store(entity3);
     QuerableTaskService tasks = new QuerableTaskService(
         new HibernateTaskQueryContext(SessionFactory));
     var t = from task in tasks
             where task.PotentialOwners.Contains(new IdentityId(userGuid1).GetIdentity())
             select task;
     Assert.IsNotNull(t);
     foreach(var task in t)
     {
         Assert.IsNotNull(task);
     }
     Assert.AreEqual(1,t.Count());
     Task foundTask = t.ElementAt(0);
     Assert.IsNotNull(foundTask);
     Assert.AreEqual(entity2.TaskId,foundTask.Id);
 }
 public void TestTaskEntityQuery()
 {
     TaskEntity entity = new TaskEntity
     {
         TaskId = new TaskId(),
         Initiator = new IdentityId().GetIdentity(),
         Priority = Priority.Normal,
         Status = TaskStatus.Created,
         Created = DateTime.UtcNow,
         Name = "Name",
         Subject = "Subject",
     };
     using (ISession session = SessionFactory.OpenSession())
     {
         session.Save(entity);
         session.Flush();
     }
     using (ISession session = SessionFactory.OpenSession())
     {
         TaskEntity te =session.Query<TaskEntity>().Where(t => t.TaskId == entity.TaskId).FirstOrDefault();
         Assert.IsNotNull(te);
     }
 }
        public void TestTaskReady()
        {
            TaskEntity entity = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name",
                Subject = "Subject"
            };

            Task task = new Task(entity)
            {
                LoggingService = new Mock<ILoggingService>().Object,
                Priority = Priority.High

            };

            TaskDao dao = new TaskDao(SessionFactory);
            task.Accept(dao);
            Task loaded;
            using (ISession session = SessionFactory.OpenSession())
            {
                TaskEntity te = session.Query<TaskEntity>().Where(t => t.TaskId == entity.TaskId).FirstOrDefault();
                loaded=new Task(te);
            }
            Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            IPrincipal p = Thread.CurrentPrincipal;
            loaded.Start();
            task.Accept(dao);
            loaded.Claim();
            task.Accept(dao);
        }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string id = this.hidID.Value;
        string status = this.ddlProcessType.SelectedValue;
        string content = this.txtDetails.Text;
        string title = this.txtTitle.Text;
        string TypeID = this.ddlTaskType.SelectedValue;

        if (TypeID == "0")
        {
            MessageBox.Show(this, "Please select type.");
            return;
        }
        if (TypeID == "1" && status == "0")
        {
            MessageBox.Show(this, "Please select Process.");
            return;
        }
        if ((TypeID != "1" || TypeID == "0") && status != "0")
        {
            MessageBox.Show(this, "Please select Process.");
            return;
        }

        try
        {
            string msg = ValidateAttachment();
            if (msg.Length > 0)
            {
                MessageBox.Show(this, msg);
                return;
            }
            string fileFullPath = string.Empty;
            string fileName = string.Empty;
            bool hasAttachment = false;
            if (this.FileUpload1.HasFile && this.FileUpload1.PostedFile.ContentLength > 0)
            {
                fileName = System.IO.Path.GetFileName(this.FileUpload1.FileName).ToLower();

                string savePath = Server.MapPath("~/") + @"Atttachment\";
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
                fileFullPath = System.IO.Path.Combine(savePath, Common.GetFullName(fileName));
                FileUpload1.SaveAs(fileFullPath);
                hasAttachment = true;
            }
            if (!hasAttachment) //no upload attachment
            {
                if (this.linkAttachment.Text.Length > 0 && this.linkAttachment.Text != "No Attachment")
                {
                    postID = Request.QueryString["TaskID"];
                    DataTable dt = taskDal.GetTaskByID(Convert.ToInt32(postID));
                    if (dt.Rows.Count > 0)
                    {
                        DataRow row = dt.Rows[0];
                        fileFullPath = row["Attachment"] == DBNull.Value ? "" : row["Attachment"].ToString();
                        fileName = row["fileName"] == DBNull.Value ? "" : row["fileName"].ToString();
                    }
                }
            }

            TaskEntity tt = new TaskEntity();
            tt.ID = Convert.ToInt32(id);
            tt.Status = status;
            tt.Content = content;
            tt.Title = title;
            tt.Attachment = fileFullPath;
            tt.FileName = fileName;
            tt.ProcessID = status;
            tt.TypeID = TypeID;
            if (taskDal.UpdateTask(tt))
            {
                MessageBox.Show(this, "update task successfully.");
                postID = Request.QueryString["TaskID"];
                Response.Redirect("ShowTask.aspx?TaskID=" + postID);
            }
         
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message);
        }


    }
        public void TestStoreTaskComments()
        {
            TaskEntity entity = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name",
                Subject = "Subject",
                Comments = new List<TaskComment>()
            };
            entity.Comments.Add(new TaskComment
                                    {
                                        TimeStamp = DateTime.UtcNow,
                                        Comment = "comment 1",
                                        UserId = new IdentityId()
                                    });
            entity.Comments.Add(new TaskComment
            {
                TimeStamp = DateTime.UtcNow,
                Comment = "comment 2",
                UserId = new IdentityId()
            });

            entity.Comments.Add(new TaskComment
            {
                TimeStamp = DateTime.UtcNow,
                Comment = "comment 3",
                UserId = new IdentityId()
            });
            ISession session = SessionFactory.OpenSession();
            session.Save(entity);
            session.Flush();
            TaskEntity te  = session.Get<TaskEntity>(1);
            Assert.IsNotNull(te);
        }
Example #50
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string id = this.hidID.Value;
        string TypeID = this.ddlTaskType.TypeID;
        string processID = this.ddlProcessType.ProcessingID;
        string content = this.txtDetails.Text.Trim();
        string title = this.txtTitle.Text.Trim();

        if (title.Length == 0)
        {
            MessageBox.Show(this, "Title cannot be empty.");
            return;
        }

        if (content.Length == 0)
        {
            MessageBox.Show(this, "Content cannot be empty.");
            return;
        }
        if (TypeID == "0")
        {
            MessageBox.Show(this, "Please select type.");
            return;
        }
        if (TypeID =="1" && processID == "0")
        {
            MessageBox.Show(this, "Please select Process.");
            return;
        }
        if ((TypeID != "1" || TypeID == "0") && processID!="0")
        {
            MessageBox.Show(this, "Please select Process.");
            return;
        }
        try
        {
         
            string msg = ValidateAttachment();
            if (msg.Length > 0)
            {
                MessageBox.Show(this, msg);
                return;
            }
            string fileFullPath = string.Empty;
            string fileName = string.Empty;
            if (this.FileUpload1.HasFile && this.FileUpload1.PostedFile.ContentLength > 0)
            {
                fileName = System.IO.Path.GetFileName(this.FileUpload1.FileName).ToLower();
                string savePath = Server.MapPath("~/") + @"Atttachment\";
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
                fileFullPath = System.IO.Path.Combine(savePath, Common.GetFullName(fileName));
                FileUpload1.SaveAs(fileFullPath);
            }

            TaskEntity tt = new TaskEntity();
            tt.Content = content;
            tt.TypeID = TypeID;
            tt.ProcessID = processID;
            tt.UserID = userID;
            tt.Title = title;
            tt.CreateTime = DateTime.Now;
            tt.Attachment = fileFullPath;
            tt.FileName = fileName;
            if (taskDal.AddTask(tt))
            {
                MessageBox.Show(this, "Add task successfully.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message);
        }
    }
 /// <summary> 根据 <see cref="PartakerEntity.Task"/> 与 <see cref="PartakerEntity.Staff"/> 检查是否<b>不</b>存在相应的 <see cref="PartakerEntity"/>. </summary>
 public static PartakerNotExistsResult CheckStaff(TaskEntity task, StaffEntity staff)
 {
     if (task == null) throw new ArgumentNullException(nameof(task));
     if (staff == null) throw new ArgumentNullException(nameof(staff));
     return CheckStaff(task, staff.Id);
 }
Example #52
0
    public bool UpdateTask(TaskEntity entity)
    {
        try
        {
            ProcessType p = new ProcessType(entity.ProcessID);

            string sql = @"update task set status=@status, CompleteTime=@CompleteTime,
                           Title=@Title,Content=@Content,Attachment=@Attachment,FileName=@FileName,ProcessID=@ProcessID,TypeID=@TypeID where id=@id";
            SqlParameter[] par = new SqlParameter[9];
            par[0] = new SqlParameter("@status", entity.Status);
            if (p.ProcessStatus == ProcessType.Process_Status.Compeleted)
            {
                par[1] = new SqlParameter("@CompleteTime", DateTime.Now);
            }
            else
            {
                par[1] = new SqlParameter("@CompleteTime", DBNull.Value);
            }
            par[2] = new SqlParameter("@Title",entity.Title);
            par[3] = new SqlParameter("@Content", entity.Content);
            par[4] = new SqlParameter("@Attachment", entity.Attachment);
            par[5] = new SqlParameter("@FileName", entity.FileName);
            par[6] = new SqlParameter("@ProcessID", entity.ProcessID);
            par[7] = new SqlParameter("@TypeID", entity.TypeID);
            par[8] = new SqlParameter("@id", entity.ID);
            int result = SqlHelper.ExecuteSql(sql, par);
            return result > 0;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 public void TestStoreFetchSubtasks()
 {
     TaskEntity entity = new TaskEntity
     {
         TaskId = new TaskId(),
         Initiator = new IdentityId().GetIdentity(),
         Priority = Priority.Normal,
         Status = TaskStatus.Created,
         Created = DateTime.UtcNow,
         Name = "Name",
         Subject = "Subject",
     };
     int subtaskId;
     using (ISession session = SessionFactory.OpenSession())
     {
         int parentId = Convert.ToInt32(session.Save(entity));
         session.Flush();
         TaskEntity te = session.Get<TaskEntity>(parentId);
         TaskEntity subtask = new TaskEntity
                                  {
                                      TaskId = new TaskId(),
                                      Initiator = new IdentityId().GetIdentity(),
                                      Priority = Priority.Normal,
                                      Status = TaskStatus.Created,
                                      Created = DateTime.UtcNow,
                                      Name = "Child Name",
                                      Subject = "Child Subject",
                                      Comments = new List<TaskComment>(),
                                      Parent = te
                                  };
         subtaskId = Convert.ToInt32(session.Save(subtask));
         session.Flush();
     }
     using (ISession session = SessionFactory.OpenSession())
     {
         TaskEntity teSubtask = session.Get<TaskEntity>(subtaskId);
         Assert.IsNotNull(teSubtask.Parent);
         Assert.AreEqual(entity.TaskId, teSubtask.Parent.TaskId);
         TaskEntity teParent = session.Load<TaskEntity>(((TaskEntity)teSubtask.Parent).Id);
         Assert.IsNotNull(teParent);
         Assert.IsNotNull(teParent.Subtasks);
         Assert.AreEqual(1, teParent.Subtasks.Count());
     }
 }
        public void SetUp()
        {
            // Create a user cloner:
            _userCloner = new EntityCloner<UserEntity>();

            _userCloner.Copied.Add(
                UserFields.Name,
                UserFields.Username,
                UserFields.Password,
                UserFields.WindowsDomainAndUsername,
                UserFields.Telephone,
                UserFields.CompanyName,
                UserFields.EmailAddress,
                UserFields.CultureName,
                UserFields.GrantedSecurityLevel);

            _userCloner.IgnoredRelations.Add(
                UserEntity.PrefetchPathCertificate,
                UserEntity.PrefetchPathCreatedDocuments,
                UserEntity.PrefetchPathEntryCollectionViaTimesheetEntry,
                UserEntity.PrefetchPathModifiedDocuments,
                UserEntity.PrefetchPathNotifications,
                UserEntity.PrefetchPathProjects,
                UserEntity.PrefetchPathSigningRequest,
                UserEntity.PrefetchPathTaskCollectionViaTimesheetEntry,
                UserEntity.PrefetchPathTasks,
                UserEntity.PrefetchPathActivities,
                UserEntity.PrefetchPathWatches);

            // Create a task cloner:
            _taskCloner = new EntityCloner<TaskEntity>();

            _taskCloner.Copied.Add(
                TaskFields.Title,
                TaskFields.Status,
                TaskFields.AssignedToId,
                TaskFields.Priority,
                TaskFields.ReplacedById,
                TaskFields.FirstEntryDateUtc,
                TaskFields.LastEntryDateUtc);

            _taskCloner.Ignored.Add(
                TaskFields.DueAtUtc,
                TaskFields.DueAtPrecision,
                TaskFields.DueAtReason,
                TaskFields.OptimisticEffortEstimate,
                TaskFields.LikelyEffortEstimate,
                TaskFields.PessimisticEffortEstimate,
                TaskFields.ActualEffort);

            _taskCloner.IgnoredRelations.Add(
                TaskEntity.PrefetchPathEntries,
                TaskEntity.PrefetchPathToLinks,
                TaskEntity.PrefetchPathFromLinks,
                TaskEntity.PrefetchPathProjectAssignments,
                TaskEntity.PrefetchPathReplaces,
                TaskEntity.PrefetchPathTimesheetEntry,
                TaskEntity.PrefetchPathProjects,
                TaskEntity.PrefetchPathWatchers);

            _taskCloner.IgnoredRelations.Add(
                TaskEntity.PrefetchPathEntryCollectionViaTimesheetEntry,
                TaskEntity.PrefetchPathUserCollectionViaTimesheetEntry);

            _taskCloner.CopiedRelations.Add(TaskEntity.PrefetchPathAssignedTo, _userCloner);
            _taskCloner.CopiedRelations.Add(TaskEntity.PrefetchPathReplacedBy, _taskCloner);

            EntityCloner<WatchEntity> watchCloner = new EntityCloner<WatchEntity>();

            watchCloner.Copied.Add(
                WatchFields.TaskId,
                WatchFields.UserId);

            watchCloner.IsRecursive = false;

            _taskCloner.CopiedRelations.Add(TaskEntity.PrefetchPathWatches, watchCloner);

            // Create a task:
            _task = new TaskEntity();

            _task.Id = 12;
            _task.Title = "Buy Jessica some flowers to show appreciation for many a coffee";
            _task.Status = "open";
            _task.Priority = 150;
            _task.DueAtUtc = DateTime.UtcNow;

            // Create a user:
            _user = new UserEntity();
            _user.Id = 123;
            _user.Name = "Julie Von Twinkle";

            _task.AssignedTo = _user;
        }
        private void FetchPopulatedTaskFromDatabase()
        {
            EntityCollection<TaskEntity> tasks = new EntityCollection<TaskEntity>();

            RelationPredicateBucket filter = new RelationPredicateBucket(TaskFields.AssignedToId != DBNull.Value);

            // Join to ensure that we have at least one entry.
            filter.Relations.Add(TaskEntity.Relations.EntryEntityUsingTaskId);

            PrefetchPath2 path = new PrefetchPath2(EntityType.TaskEntity);
            path.Add(TaskEntity.PrefetchPathAssignedTo);
            IPrefetchPathElement2 entriesElement = path.Add(TaskEntity.PrefetchPathEntries);

            entriesElement.SubPath.Add(EntryEntity.PrefetchPathUser);

            _adapter.FetchEntityCollection(tasks, filter, 1, null, path);

            _task = tasks[0];
        }
 /// <summary>
 /// Visits the specified entity.
 /// </summary>
 /// <param name="entity">The entity.</param>
 public void Visit(TaskEntity entity)
 {
     if(OnEntityVisit!=null)
         OnEntityVisit.Invoke(entity);
 }
        public void TestPersistRoleAssignment()
        {
            TaskEntity entity = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name",
                Subject = "Subject"
            };

            Task task = new Task(entity)
            {
                LoggingService = new Mock<ILoggingService>().Object,
                Priority = Priority.High

            };

            TaskDao dao = new TaskDao(SessionFactory);
            task.Accept(dao);
            task.PotentialOwners.Add(new IdentityId().GetIdentity());
            task.PotentialOwners.Add(new IdentityId().GetIdentity());
            task.Recepients.Add(new IdentityId().GetIdentity());
            task.Recepients.Add(new IdentityId().GetIdentity());
            task.Recepients.Add(new IdentityId().GetIdentity());
            task.Recepients.Add(new IdentityId().GetIdentity());
            task.BusinessAdministrators.Add(new IdentityId().GetIdentity());
            task.Accept(dao);

            using (ISession session = SessionFactory.OpenSession())
            {
                TaskEntity te = session.Query<TaskEntity>().Where(t => t.TaskId == entity.TaskId).FirstOrDefault();
            }
        }