// Main Detail public ViewResult Detail(string taskcode) { Worktask worktask = repository.Detail(taskcode); if (worktask == null) { return(View("Index")); } worktask.loadMetaInfo(repository, accRepository); foreach (var item in worktask.Comment) { //item.Username = repository.Accounts.Where(x => x.UID == item.AccountID).FirstOrDefault().UserName; item.RelativeTime = GetRelativeTime(item.CommentDate); } List <Event> eventlist = new List <Event>(); foreach (var transition in worktask.WorkflowInstance.CurrentState.TransitionTo) { eventlist.Add(transition.Event); } ViewBag.NextStatus = HTMLHelperExtensions.GenerateStatusHTMLCode(worktask.WorkflowInstance.CurrentStateID, worktask.WorktaskID, (IEnumerable <Event>)eventlist); var attachmentModel = worktask.Attachment.ToList(); return(View(worktask)); }
public ActionResult MoveTask(MoveTaskViewModel movetask) { int currentUID = AccountHelper.GetCurrentUser(User.Identity.Name).UID; if (ModelState.IsValid) { Worktask newObject = repository.Worktasks.Where(x => x.WorktaskID == movetask.WorktaskID).FirstOrDefault(); newObject = repository.Detail(newObject.WorktaskID); newObject.loadMetaInfo(repository, accRepository); Worktask oldObject = newObject.clone(); if (newObject != null) { newObject.BoardID = movetask.BoardID; newObject.WorkflowInstance.CurrentStateID = movetask.StateID; List <DiffInfo> diffInfos = newObject.Compare(oldObject); var diff = CompareObjExtensions.GenerateDiff("Cập nhật", diffInfos, currentUID, oldObject.WorktaskID); if (repository.SaveWorktask(newObject)) { if (repository.SaveHistory(diff)) { TempData["message"] = string.Format("Chuyển bảng công việc cho {0} thành công!", oldObject.Identify); return(RedirectToAction("Detail", new { taskcode = oldObject.Identify })); } } } return(View(movetask)); } else { TempData["message"] = string.Format(GetModelErrorMessages(ModelState)); return(View(movetask)); } }
public Worktask DeleteWorktask(int id) { Worktask dbEntry = context.Worktasks.Find(id); if (dbEntry != null) { //remove worktasks //context.Worktasks.Remove(dbEntry); // Please set DelFlag = 1 in Production dbEntry.DeleteFlag = true; //remove attachments var attachments = context.Attachments.Where(x => x.WorktaskID == id).ToList(); foreach (var item in attachments) { // Hard delete //context.Attachment.Remove(item); // soft delete item.DeleteFlag = true; } context.SaveChanges(); } return(dbEntry); }
/// <summary> /// Add attachment into Worktask. /// Becareful to save Attachment to db BEFORE call this function /// </summary> /// <param name="worktaskId">Task ID of worktask</param> /// <param name="attachment">Attachment instance</param> /// <returns>True: Success, False: Incomplete</returns> public async System.Threading.Tasks.Task <string> SaveAttachmentIntoTask(int worktaskId, Attachment attachment) { string saveResult = ""; Worktask worktask = context.Worktasks.Where(w => w.WorktaskID == worktaskId).FirstOrDefault(); // Make sure task is get correctly if (worktask != null && worktask.WorktaskID > 0) { var list = worktask.Attachment as List <Attachment>; list.Add(attachment); try { await context.SaveChangesAsync(); } catch (Exception ex) { // ex saveResult += ex.Message; } } return(saveResult); }
public string GetTaskDisplayValue(int taskId, string value, string propname) { Worktask task = this.worktaskRepository.Detail(taskId); if (task != null) { if (propname.Equals("Status")) { int id = (int)(task.WorkflowInstance.WorkflowID == null ? 0 : task.WorkflowInstance.WorkflowID); return(WorkflowService.GetInstance().GetState(id, int.Parse(value)).Name); } else if (propname.Equals("Priority")) { return(CategoryService.GetInstance().GetCategoryName(int.Parse(value), Contain.CatType.Priority)); } else if (propname.Equals("TaskType")) { return(CategoryService.GetInstance().GetCategoryName(int.Parse(value), Contain.CatType.Category)); } else if (propname.Equals("BoardID")) { return(task.Board.Title); } else if (propname.Equals("Assignee")) { return(AccountHelper.GetUserFullname(task.AssigneeAcc.UserName)); } else if (propname.Equals("Reporter")) { return(AccountHelper.GetUserFullname(task.ReporterAcc.UserName)); } } return(value); }
public static WorktaskDto ToWorktaskDto(this Worktask worktask) { return(new WorktaskDto { TaskId = worktask.ID, StatusId = worktask.StatusId, StatusName = worktask.Status.Name, Subject = worktask.Subject, Text = worktask.Text, AuthorId = worktask.AuthorId, AuthorName = worktask.Author.FIO, EditorId = worktask.EditorId, EditorName = worktask.Editor.FIO, CreateDate = worktask.CreateDate.ToString("yyyy-MM-dd"), UpdateDate = worktask.UpdateDate.ToString("yyyy-MM-dd"), CommentCount = worktask.Comments.Count, CanBeDeleted = worktask.Status.WorktaskAccesses.Any(a => a.AccessType.Name == "Delete"), CanBeEdited = worktask.Status.WorktaskAccesses.Any(a => a.AccessType.Name == "Edit"), CanTransitToStatuses = worktask.Status.FromStatusRoutes .Select(r => new Transition { Status = r.ToStatusId, NeedComment = r.NeedComment }).ToArray(), Comments = worktask.Comments.Select(c => c.ToCommentDto()).ToArray(), }); }
public ActionResult Delete(int id) { Worktask deletedProduct = repository.DeleteWorktask(id); if (deletedProduct != null) { TempData["message"] = string.Format("{0} đã xóa.", deletedProduct.Identify); } return(RedirectToAction("Index")); }
public bool CreateSingleIndex(Worktask worktask) { try { var result = client.Index(worktask); return(result.IsValid); } catch { return(false); } }
public static List <TaskHistory> GenerateDiff(string action, List <DiffInfo> diffInfo, int updateUser, int taskID) { List <TaskHistory> res = new List <TaskHistory>(); Worktask task = WorktaskService.GetInstance().GetTask(taskID); foreach (var item in diffInfo) { string displayTitle = item.Title; switch (item.DisplayType) { case DisplayTypeE.UserId: item.OldValue = (item.OldValue == null ? String.Empty : AccountHelper.GetUserById((int)item.OldValue).DisplayName2); item.NewValue = (item.NewValue == null ? String.Empty : AccountHelper.GetUserById((int)item.NewValue).DisplayName2); break; case DisplayTypeE.BoardId: item.OldValue = (item.OldValue == null ? String.Empty : BoardService.GetInstance().GetBoard((int)item.OldValue).Title); item.NewValue = (item.NewValue == null ? String.Empty : BoardService.GetInstance().GetBoard((int)item.NewValue).Title); break; case DisplayTypeE.WorkflowState: int id = (int)(task.WorkflowInstance.WorkflowID == null ? 0 : task.WorkflowInstance.WorkflowID); item.OldValue = (item.OldValue == null ? String.Empty : WorkflowService.GetInstance().GetState(id, (int)item.OldValue).Name); item.NewValue = (item.NewValue == null ? String.Empty : WorkflowService.GetInstance().GetState(id, (int)item.NewValue).Name); break; case DisplayTypeE.CategoryPriority: item.OldValue = (item.OldValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.OldValue, Contain.CatType.Priority)); item.NewValue = (item.NewValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.NewValue, Contain.CatType.Priority)); break; case DisplayTypeE.CategoryTaskType: item.OldValue = (item.OldValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.OldValue, Contain.CatType.Category)); item.NewValue = (item.NewValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.NewValue, Contain.CatType.Category)); break; case DisplayTypeE.CategoryCompany: item.OldValue = (item.OldValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.OldValue, Contain.CatType.Company)); item.NewValue = (item.NewValue == null ? String.Empty : CategoryService.GetInstance().GetCategoryName((int)item.NewValue, Contain.CatType.Company)); break; case DisplayTypeE.Date: item.OldValue = (item.OldValue == null ? String.Empty : ((DateTime)item.OldValue).ToString("dd/MM/yyyy")); item.NewValue = (item.NewValue == null ? String.Empty : ((DateTime)item.NewValue).ToString("dd/MM/yyyy")); break; } res.Add(CompareObjExtensions.GenerateDiff(action, displayTitle, (item.NewValue == null ? String.Empty : item.NewValue.ToString()), (item.OldValue == null ? String.Empty : item.OldValue.ToString()), updateUser, taskID)); } return(res); }
public Worktask DetailInfo(Worktask task) { try { task.AssigneeAcc = context.Accounts.Where(a => a.UID == task.Assignee).FirstOrDefault(); task.OwnerAcc = context.Accounts.Where(a => a.UID == task.Owner).FirstOrDefault(); task.ReporterAcc = context.Accounts.Where(a => a.UID == task.Reporter).FirstOrDefault(); task.TaskMetas = context.WorkTaskMetas.Where(m => m.WorktaskID == task.WorktaskID).ToList(); return(task); } catch { throw; } }
public ActionResult UpdateStatus(int worktaskId, int nextEvent) { var worktask = repository.Worktasks.Where(x => x.WorktaskID == worktaskId).FirstOrDefault(); worktask = repository.Detail(worktask.WorktaskID); State curState = worktask.WorkflowInstance.CurrentState; State nextState = null; int currentUID = AccountHelper.GetCurrentUser(User.Identity.Name).UID; Transition transition = curState.TransitionTo.Where(t => t.EventID == nextEvent).FirstOrDefault(); if (transition != null) { nextState = transition.ToState; } if (curState.Type == (int)Contain.StateType.Init && nextState.Type != (int)Contain.StateType.Init) { worktask.ActualStartDate = DateTime.Now; } if (curState.Type != (int)Contain.StateType.End && nextState.Type == (int)Contain.StateType.End) { worktask.ActualEndDate = DateTime.Now; } var diff = new List <TaskHistory>(); Worktask oldObject = worktask.clone(); // go to next state worktask.WorkflowInstance.CurrentState = nextState; worktask.Status = nextState.ID; if (repository.SaveWorktask(worktask)) { List <DiffInfo> diffInfos = worktask.Compare(oldObject); diff = CompareObjExtensions.GenerateDiff("Cập nhật", diffInfos, currentUID, oldObject.WorktaskID); repository.SaveHistory(diff); TempData["message"] = string.Format("Thông tin công việc {0} lưu thành công!", worktask.Identify); return(RedirectToAction("Detail", new { taskcode = worktask.Identify })); } return(View()); }
public ActionResult InsertTask(Worktask worktask) { int currentUID = AccountHelper.GetCurrentUser(User.Identity.Name).UID; ElasticIndexService eService = new ElasticIndexService(); Worktask oldObject = null; if (ModelState.IsValid) { var isNew = false; // Assign Current user AS Owner, Assignee, Reporter if (worktask.Owner == 0) { worktask.Owner = currentUID; } if (worktask.Assignee == 0) { worktask.Assignee = currentUID; } if (worktask.Reporter == null || worktask.Reporter == 0) { worktask.Reporter = currentUID; } if (worktask.TaskType == 0) { worktask.TaskType = int.Parse(CategoryService.GetInstance().GetCategoryList(Contain.CatType.Category).ElementAt(1).Value); } if (worktask.Priority == 0) { worktask.Priority = int.Parse(CategoryService.GetInstance().GetCategoryList(Contain.CatType.Priority).ElementAt(1).Value); } if (worktask.WorktaskID == 0) { isNew = true; worktask.BoardID = this.GetLastViewedBoardId(User.Identity.Name); worktask.TaskMetas = new List <WorkTaskMetas>(); worktask = WorktaskService.GetInstance().loadMetaInfoFromRequest(worktask, Request); worktask.loadMetaInfo(repository, accRepository); // create workflow instance Board board = this.boardRepository.Get(worktask.BoardID); Workflow wf = board.Workflow; State firstState = wf.States.Where(s => s.Type == (int)Contain.StateType.Init).FirstOrDefault(); WorkflowInstance wfi = new WorkflowInstance() { WorkflowID = wf.ID, CurrentStateID = (firstState != null ? firstState.ID : 0) }; worktask.WorkflowInstance = wfi; worktask.Status = firstState.ID; } else { worktask = WorktaskService.GetInstance().loadMetaInfoFromRequest(worktask, Request); worktask.loadMetaInfo(repository, accRepository); oldObject = repository.Worktasks.Where(x => x.WorktaskID == worktask.WorktaskID).FirstOrDefault(); oldObject = repository.Detail(oldObject.WorktaskID); oldObject.loadMetaInfo(repository, accRepository); } var diff = new List <TaskHistory>(); if (repository.SaveWorktask(worktask)) { //save history worktask when create new string action = "Cập nhật"; if (isNew) { // Save data path for the new task string dataPathRoot = HostingEnvironment.MapPath(WebConfigurationManager.AppSettings["DataDirectoryRoot"]); string taskDataPath = Path.Combine(dataPathRoot, worktask.WorktaskID.ToString()); worktask.DataPath = taskDataPath; Directory.CreateDirectory(taskDataPath); action = "Tạo mới"; } List <DiffInfo> diffInfos = worktask.Compare(oldObject); diff = CompareObjExtensions.GenerateDiff(action, diffInfos, currentUID, worktask.WorktaskID); repository.SaveHistory(diff); foreach (var item in worktask.Attachment) { var text = String.Empty; if (System.IO.File.Exists(item.StoredPath)) { text = new TextExtractor().Extract(item.StoredPath).Text; } item.Metadata = text.Replace("\r", string.Empty).Replace("\n", string.Empty); } if (repository.SaveAttachmentFile(worktask)) { //save history diff = CompareObjExtensions.DetailedCompare(null, worktask.Attachment, currentUID, worktask.WorktaskID, isNew); if (repository.SaveHistory(diff)) { // Save Index in Elastic eService.CreateSingleIndex(repository.Detail(worktask.WorktaskID)); TempData["message"] = string.Format("Thông tin công việc {0} lưu thành công!", worktask.Identify); return(Json(new { taskId = worktask.WorktaskID, attachment = worktask.Attachment.Select(x => new { AttachmentID = x.AttachmentID, Name = x.Name }), success = true, redirectUrl = Url.Action("Detail", new { taskcode = worktask.Identify }) }, JsonRequestBehavior.AllowGet)); } } // Save Index in Elastic eService.CreateSingleIndex(repository.Detail(worktask.WorktaskID)); TempData["message"] = string.Format("Thông tin công việc {0} lưu thành công!", worktask.Identify); return(Json(new { taskId = worktask.WorktaskID, success = true, redirectUrl = Url.Action("Detail", new { taskcode = worktask.Identify }) }, JsonRequestBehavior.AllowGet)); } TempData["message"] = string.Format("Lưu không thành công"); return(Json(new { taskId = 0, success = false, message = TempData["message"] }, JsonRequestBehavior.AllowGet)); } else { TempData["message"] = string.Format(GetModelErrorMessages(ModelState)); return(Json(new { taskId = 0, success = false, message = TempData["message"] }, JsonRequestBehavior.AllowGet)); } }
public ActionResult InsertTask2(Worktask worktask) { // NOT ModelState.IsValid if (!ModelState.IsValid) { TempData["message"] = string.Format(GetModelErrorMessages(ModelState)); return(Json(new { taskId = 0, success = false, message = TempData["message"] }, JsonRequestBehavior.AllowGet)); } // ModelState.IsValid int currentUID = AccountHelper.GetCurrentUser(User.Identity.Name).UID; ElasticIndexService eService = new ElasticIndexService(); // Assign Current user AS Owner, Assignee, Reporter if (worktask.Owner == 0) { worktask.Owner = currentUID; } if (worktask.Assignee == 0) { worktask.Assignee = currentUID; } if (worktask.Reporter == 0) { worktask.Reporter = currentUID; } if (worktask.TaskType == 0) { worktask.TaskType = int.Parse(CategoryService.GetInstance().GetCategoryList(Contain.CatType.Category).ElementAt(1).Value); } if (worktask.Priority == 0) { worktask.Priority = int.Parse(CategoryService.GetInstance().GetCategoryList(Contain.CatType.Priority).ElementAt(1).Value); } string[] selectedtaskcodes = Request.Params.GetValues("RelatedTaskValue[]"); int relatedtaskmetatype = catRepository.Categories.Where(c => c.CatType == (int)Contain.CatType.MetaType && c.CategoryName.Equals("metastring")).FirstOrDefault().CatValue; var isNew = false; // Set relate task if (worktask.WorktaskID == 0) { isNew = true; worktask.BoardID = this.GetLastViewedBoardId(User.Identity.Name); // create workflow instance Board board = this.boardRepository.Get(worktask.BoardID); Workflow wf = board.Workflow; State firstState = wf.States.Where(s => s.Type == (int)Contain.StateType.Init).FirstOrDefault(); WorkflowInstance wfi = new WorkflowInstance() { WorkflowID = wf.ID, CurrentStateID = (firstState != null ? firstState.ID : 0) }; worktask.WorkflowInstance = wfi; worktask.Status = firstState.ID; } worktask.TaskMetas = new List <WorkTaskMetas>(); if (selectedtaskcodes != null && selectedtaskcodes.Length > 0) { foreach (string code in selectedtaskcodes) { worktask.TaskMetas.Add(new WorkTaskMetas() { MetaKey = "RelatedTask", MetaValue = code, MetaType = relatedtaskmetatype }); } } else { if (!isNew) { var oldObject = repository.Worktasks.Where(x => x.WorktaskID == worktask.WorktaskID).FirstOrDefault(); oldObject = repository.Detail(oldObject.WorktaskID); worktask.TaskMetas = oldObject.TaskMetas; } } //Save data if (!repository.SaveWorktask(worktask)) { TempData["message"] = string.Format("Lưu không thành công"); return(Json(new { taskId = 0, success = false, message = TempData["message"] }, JsonRequestBehavior.AllowGet)); } var diff = new List <TaskHistory>(); //save history worktask when create new if (isNew) { // Save data path for the new task string dataPathRoot = HostingEnvironment.MapPath(WebConfigurationManager.AppSettings["DataDirectoryRoot"]); string taskDataPath = Path.Combine(dataPathRoot, worktask.WorktaskID.ToString()); worktask.DataPath = taskDataPath; Directory.CreateDirectory(taskDataPath); diff = CompareObjExtensions.DetailedCompare(null, worktask, currentUID, worktask.WorktaskID, isNew); } repository.SaveHistory(diff); //Save attach files foreach (var item in worktask.Attachment) { var text = String.Empty; if (System.IO.File.Exists(item.StoredPath)) { text = new TextExtractor().Extract(item.StoredPath).Text; } item.Metadata = text.Replace("\r", string.Empty).Replace("\n", string.Empty); } if (repository.SaveAttachmentFile(worktask)) // << Cái này không save được thì có rolback không? { //save history diff = CompareObjExtensions.DetailedCompare(null, worktask.Attachment, currentUID, worktask.WorktaskID, isNew); if (!repository.SaveHistory(diff)) { TempData["message"] = string.Format("Lưu không thành công"); return(Json(new { taskId = 0, success = false, message = TempData["message"] }, JsonRequestBehavior.AllowGet)); } } // Save Index in Elastic eService.CreateSingleIndex(repository.Detail(worktask.WorktaskID)); TempData["message"] = string.Format("Thông tin công việc {0} lưu thành công!", worktask.Identify); return(Json(new { taskId = worktask.WorktaskID, success = true, redirectUrl = Url.Action("Detail", new { taskcode = worktask.Identify }) }, JsonRequestBehavior.AllowGet)); }
public bool SaveAttachmentFile(Worktask worktask) { var result = true; try { if (worktask.WorktaskID != 0) { bool ocrEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["ocrEnabled"]); var dataPath = context.Worktasks.Where(w => w.WorktaskID == worktask.WorktaskID).Select(x => x.DataPath).FirstOrDefault(); foreach (var item in worktask.Attachment) { //CuongND: This should be do in Controller or Service //But I need to place here in combine with old code //Moving Files from root to correct folder // START --- Move file to new Path ---- string oldFilePath = item.StoredPath; string fileName = Path.GetFileName(item.StoredPath); string filePath = Path.GetDirectoryName(oldFilePath); //var entry = context.Attachments.Where(a => a.AttachmentID == item.AttachmentID).FirstOrDefault(); if (dataPath != filePath) { if (null == dataPath) { string taskDataPath = Path.Combine(filePath, worktask.WorktaskID.ToString()); dataPath = taskDataPath; } string newFilePath = Path.Combine(dataPath, fileName); if (!Directory.Exists(dataPath)) { Directory.CreateDirectory(dataPath); } File.Move(oldFilePath, newFilePath); item.StoredPath = newFilePath; item.WorktaskID = worktask.WorktaskID; context.Attachments.Add(item); context.SaveChanges(); // START - EXTRACT PDF TO OCR FOLDER // Start if user upload a PDF file *** (please change logic later) if (ocrEnabled) { var ocrExtension = WebConfigurationManager.AppSettings["ocrFileExtension"]; if (Path.GetExtension(fileName).ToUpper() == ocrExtension.ToUpper()) { string ocrExtractPath = WebConfigurationManager.AppSettings["ocrExtractFolder"]; if (ocrExtractPath != null) { // Move to a folder with name OCR_FolderData\TaskID\ var ocrExtractTaskPath = Path.Combine(ocrExtractPath, worktask.WorktaskID.ToString()); if (!Directory.Exists(ocrExtractTaskPath)) { Directory.CreateDirectory(ocrExtractTaskPath); } // Chop the GUID prefix the file fileName = fileName.Substring(fileName.Split('.')[0].Length + 1); fileName = worktask.WorktaskID.ToString() + "_" + item.AttachmentID + "_" + fileName; var ocrExtractTaskFile = Path.Combine(ocrExtractTaskPath, fileName); // Copy to new location File.Copy(newFilePath, ocrExtractTaskFile); } } // END - EXTRACT PDF TO OCR FOLDER } } // END --- Move file to new Path ---- } // Save change in Worktask again } context.SaveChanges(); } catch { result = false; } return(result); }
public bool SaveWorktask(Worktask worktask) { var result = true; try { if (worktask.WorktaskID == 0) { var board = context.Boards.Find(worktask.BoardID); string boardcode = board.Code.ToLower(); var lastTask = context.Worktasks.Where(t => t.Identify.StartsWith(boardcode)).OrderByDescending(t => t.Identify).FirstOrDefault(); string taskcode = String.Empty; if (lastTask != null) { int c = 0; taskcode = lastTask.Identify.Replace(boardcode, ""); if (int.TryParse(taskcode, out c)) { c += 1; taskcode = board.Code.ToLower() + c.ToString().PadLeft(6, '0'); } else { taskcode = String.Empty; } } if (taskcode.Length == 0) { int c = 1; taskcode = board.Code.ToLower() + c.ToString().PadLeft(6, '0'); } worktask.CreationDate = DateTime.Now; worktask.LastUpdateDateTime = DateTime.Now; worktask.Identify = taskcode; //worktask.Owner = "Current User"; context.Worktasks.Add(worktask); } else { int relatedtaskmetatype = context.Categories.Where(c => c.CatType == (int)Contain.CatType.MetaType && c.CategoryName.Equals("metastring")).FirstOrDefault().CatValue; Worktask dbEntry = context.Worktasks.Where(t => t.WorktaskID == worktask.WorktaskID).FirstOrDefault(); Worktask atask; if (dbEntry != null) { dbEntry.TaskType = worktask.TaskType; dbEntry.Title = worktask.Title; dbEntry.Description = worktask.Description; dbEntry.Assignee = worktask.Assignee; dbEntry.PlannedStartDate = worktask.PlannedStartDate; dbEntry.PlannedEndDate = worktask.PlannedEndDate; dbEntry.Status = worktask.Status; dbEntry.ActualStartDate = worktask.ActualStartDate; dbEntry.ActualEndDate = worktask.ActualEndDate; dbEntry.Priority = worktask.Priority; dbEntry.LastUpdateDateTime = DateTime.Now; List <WorkTaskMetas> updatedMeta = new List <WorkTaskMetas>(); updatedMeta.AddRange(worktask.TaskMetas.Select(m => m)); List <WorkTaskMetas> removedMeta = new List <WorkTaskMetas>(); foreach (WorkTaskMetas meta in dbEntry.TaskMetas) { if (updatedMeta.Count >= 0) { bool found = false; foreach (var item in updatedMeta) { if (item.MetaKey.Equals(meta.MetaKey)) { found = true; meta.MetaKey = item.MetaKey; meta.MetaType = item.MetaType; meta.MetaValue = item.MetaValue; break; } } if (!found) { removedMeta.Add(meta); } } } foreach (WorkTaskMetas removed in removedMeta) { dbEntry.TaskMetas.Remove(removed); } if (updatedMeta.Count > 0) { foreach (WorkTaskMetas item in updatedMeta) { bool found = false; foreach (WorkTaskMetas meta in dbEntry.TaskMetas) { if (item.MetaKey.Equals(meta.MetaKey)) { found = true; break; } } if (!found) { dbEntry.TaskMetas.Add(new WorkTaskMetas() { MetaKey = item.MetaKey, MetaValue = item.MetaValue, MetaType = item.MetaType }); } } } context.Entry(dbEntry).State = System.Data.Entity.EntityState.Modified; foreach (var item in removedMeta) { if (item.MetaKey.Equals("RelatedTask")) { string code = item.MetaValue; this.DeleteMeta(item.MetaID); atask = this.Detail(code); if (atask != null) { var old = atask.TaskMetas.Where(m => m.MetaKey == "RelatedTask" && m.MetaValue == worktask.Identify).FirstOrDefault(); if (old != null) { atask.TaskMetas.Remove(old); this.DeleteMeta(old.MetaID); } } } else { this.DeleteMeta(item.MetaID); } } foreach (var ameta in worktask.TaskMetas) { if (ameta.MetaKey == "RelatedTask") { atask = this.Detail(ameta.MetaValue); if (atask != null) { var old = atask.TaskMetas.Where(m => m.MetaKey == "RelatedTask" && m.MetaValue == worktask.Identify).FirstOrDefault(); if (old == null) { atask.TaskMetas.Add(new WorkTaskMetas() { MetaKey = "RelatedTask", MetaValue = worktask.Identify, MetaType = relatedtaskmetatype }); context.Entry(atask).State = System.Data.Entity.EntityState.Modified; } } } } } } int changedNo = context.SaveChanges(); if (changedNo <= 0) { return(false); } else { return(true); } } catch (DbEntityValidationException e) { result = false; foreach (var eve in e.EntityValidationErrors) { System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } } catch { result = false; //e.GetBaseException(); }; return(result); }
public Worktask loadMetaInfoFromRequest(Worktask task, HttpRequestBase request) { int stringmetatype = catRepository.Categories.Where(c => c.CatType == (int)Contain.CatType.MetaType && c.CategoryName.Equals("metastring")).FirstOrDefault().CatValue; int numbermetatype = catRepository.Categories.Where(c => c.CatType == (int)Contain.CatType.MetaType && c.CategoryName.Equals("metanumber")).FirstOrDefault().CatValue; if (task.TaskMetas == null) { task.TaskMetas = new List <WorkTaskMetas>(); } Worktask oldtask = null; if (task.WorktaskID > 0) { oldtask = worktaskRepository.Detail(task.WorktaskID); } Type t = task.GetType(); List <PropertyInfo> props = t.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(ComparableAttribute))).ToList(); DisplayTypeE displayType; MetaValueTypeE metaInfo; foreach (var p in props) { displayType = p.GetCustomAttribute <ComparableAttribute>().DisplayType; metaInfo = p.GetCustomAttribute <ComparableAttribute>().MetaInfo; int metaType = 0; switch (displayType) { case DisplayTypeE.Text: metaType = stringmetatype; break; case DisplayTypeE.Date: metaType = stringmetatype; break; case DisplayTypeE.RelatedTask: metaType = numbermetatype; break; } switch (metaInfo) { case MetaValueTypeE.MultipleValue: string[] selectedmetavalues = request.Params.GetValues(p.Name + "Value[]"); if (selectedmetavalues != null && selectedmetavalues.Length > 0) { foreach (string code in selectedmetavalues) { task.TaskMetas.Add(new WorkTaskMetas() { MetaKey = p.Name, MetaValue = code, MetaType = metaType }); } } else { if (oldtask != null) { foreach (var item in oldtask.TaskMetas) { if (item.MetaKey.Equals(p.Name)) { task.TaskMetas.Add(item); } } } } break; case MetaValueTypeE.SingleValue: WorkTaskMetas oldmetainfo = null; WorkTaskMetas metainfo = null; if (oldtask != null) { oldmetainfo = oldtask.TaskMetas.Where(m => m.MetaKey == p.Name).FirstOrDefault(); } metainfo = task.TaskMetas.Where(m => m.MetaKey == p.Name).FirstOrDefault(); if (metainfo == null && oldmetainfo == null) { metainfo = new WorkTaskMetas(); } else if (metainfo == null && oldmetainfo != null) { metainfo = oldmetainfo; } var reqvalue = p.GetValue(task); string metavalue = null; switch (displayType) { case DisplayTypeE.Text: metavalue = (reqvalue == null ? null : reqvalue.ToString()); break; case DisplayTypeE.Date: metavalue = (reqvalue == null ? null : ((DateTime)reqvalue).ToString("yyyy-MM-dd")); break; case DisplayTypeE.RelatedTask: metavalue = (reqvalue == null ? null : reqvalue.ToString()); break; default: metavalue = (reqvalue == null ? null : reqvalue.ToString()); break; } metainfo.MetaKey = p.Name; metainfo.MetaValue = metavalue; metainfo.MetaType = metaType; task.TaskMetas.Add(metainfo); break; } } return(task); }
public static void Initialize(WorktaskDbContext context) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); if (context.Worktasks.Any()) { return; } var roles = new Role[] { new Role { Name = "Оператор" }, new Role { Name = "Менеджер", }, new Role { Name = "Исполнитель", }, new Role { Name = "Администратор", }, }; context.Roles.AddRange(roles); context.SaveChanges(); var employees = new Employee[] { new Employee { FIO = "Петров Петр", RoleID = 1 }, new Employee { FIO = "Иванов Иван", RoleID = 2 }, new Employee { FIO = "Сергеев Сергей", RoleID = 3 }, new Employee { FIO = "Дмитриев Дмитрий", RoleID = 4 } }; context.Employees.AddRange(employees); context.SaveChanges(); var statuses = new Status[] { new Status { ID = "New", Name = "Новая" }, new Status { ID = "Created", Name = "Черновик" }, new Status { ID = "Completed", Name = "Выполнено" }, new Status { ID = "Accepted", Name = "В обработке" }, new Status { ID = "Clarified", Name = "На согласовании" }, new Status { ID = "Declined", Name = "Отклонено" } }; context.WorktaskStatuses.AddRange(statuses); context.SaveChanges(); var routes = new StatusRoute[] { new StatusRoute { FromStatusId = "Created", ToStatusId = "Accepted" }, new StatusRoute { FromStatusId = "Created", ToStatusId = "Declined", NeedComment = true }, new StatusRoute { FromStatusId = "Accepted", ToStatusId = "Completed" }, new StatusRoute { FromStatusId = "Accepted", ToStatusId = "Clarified", NeedComment = true }, }; context.StatusRoutes.AddRange(routes); context.SaveChanges(); var tasks = new Worktask[] { new Worktask { ID = "1", StatusId = "Created", Subject = "test", Text = "test", AuthorId = 1, EditorId = 1, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, }, new Worktask { ID = "2", StatusId = "Completed", Subject = "test", Text = "test", AuthorId = 1, EditorId = 1, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, }, new Worktask { ID = "3", StatusId = "Accepted", Subject = "test", Text = "test", AuthorId = 1, EditorId = 1, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, }, new Worktask { ID = "4", StatusId = "Declined", Subject = "test", Text = "test", AuthorId = 1, EditorId = 1, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, }, }; context.Worktasks.AddRange(tasks); context.SaveChanges(); var accessTypes = new AccessType[] { new AccessType { Name = "Create" }, new AccessType { Name = "Read" }, new AccessType { Name = "Edit" }, new AccessType { Name = "Delete" }, }; context.AccessTypes.AddRange(accessTypes); context.SaveChanges(); var accesses = new StatusAccess[] { new StatusAccess { RoleID = 1, AccessTypeId = accessTypes.Single(a => a.Name == "Create").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "New").ID, }, new StatusAccess { RoleID = 1, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = true, StatusId = statuses.Single(o => o.ID == "Created").ID, }, new StatusAccess { RoleID = 2, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Created").ID, }, new StatusAccess { RoleID = 2, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Clarified").ID, }, new StatusAccess { RoleID = 2, AccessTypeId = accessTypes.Single(a => a.Name == "Edit").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Created").ID, }, new StatusAccess { RoleID = 3, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Accepted").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Accepted").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Declined").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Completed").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Clarified").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Read").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Created").ID, }, new StatusAccess { RoleID = 1, AccessTypeId = accessTypes.Single(a => a.Name == "Edit").ID, OnlyAuthored = true, StatusId = statuses.Single(o => o.ID == "Created").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Delete").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Completed").ID, }, new StatusAccess { RoleID = 4, AccessTypeId = accessTypes.Single(a => a.Name == "Delete").ID, OnlyAuthored = false, StatusId = statuses.Single(o => o.ID == "Declined").ID, }, }; context.WorktaskAccesses.AddRange(accesses); context.SaveChanges(); var routeAccesses = new StatusRouteAccess[] { new StatusRouteAccess { RoleId = roles.Single(r => r.Name == "Менеджер").ID, StatusRouteId = 3, }, new StatusRouteAccess { RoleId = roles.Single(r => r.Name == "Менеджер").ID, StatusRouteId = 4, }, new StatusRouteAccess { RoleId = roles.Single(r => r.Name == "Исполнитель").ID, StatusRouteId = 1, }, new StatusRouteAccess { RoleId = roles.Single(r => r.Name == "Исполнитель").ID, StatusRouteId = 2, }, }; context.StatusRouteAccesses.AddRange(routeAccesses); context.SaveChanges(); var comments = new Comment[] { new Comment { AuthorId = 1, CreateDate = DateTime.Now, Text = "bla", WorktaskId = "1" }, new Comment { AuthorId = 2, CreateDate = DateTime.Now, Text = "bla", WorktaskId = "1" }, new Comment { AuthorId = 3, CreateDate = DateTime.Now, Text = "bla", WorktaskId = "2" }, new Comment { AuthorId = 4, CreateDate = DateTime.Now, Text = "bla", WorktaskId = "3" }, }; context.Comments.AddRange(comments); context.SaveChanges(); }
public void DeleteId(Worktask worktask) { var bulkResponse = client.Delete <Worktask>("AVegMX6OEI1lsaTKVC2v"); }
public async Task <IHttpActionResult> Upload([FromBody] UploadFileModel incomingFile) { if (!Request.Content.IsMimeMultipartContent()) { return(Ok(new { isSuccess = false, message = "Not a MIME MultiPart Content." })); } // Identify requested worktask var intTaskId = 0; if (!int.TryParse(incomingFile.TaskId, out intTaskId)) { return(NotFound()); } var intAttachedId = 0; if (!int.TryParse(incomingFile.AttachedId, out intAttachedId)) { return(NotFound()); } // Get the appropiate worktask by ID (int) Worktask worktask = repository.Detail(intTaskId); if (worktask == null) { return(NotFound()); } Attachment attached = worktask.Attachment.Where(p => p.AttachmentID == intAttachedId && p.DeleteFlag == false).FirstOrDefault(); if (attached == null) { return(NotFound()); } // Await task to get file Stream requestStream = await Request.Content.ReadAsStreamAsync(); var mProvider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(mProvider); // START --- Get server root path --- string dataPathRoot = HostingEnvironment.MapPath(WebConfigurationManager.AppSettings["DataDirectoryRoot"]); if (!Directory.Exists(dataPathRoot)) { Directory.CreateDirectory(dataPathRoot); } string taskPath = Path.Combine(dataPathRoot, intTaskId.ToString()); if (!Directory.Exists(taskPath)) { Directory.CreateDirectory(taskPath); } // END --- Get server root path --- foreach (var file in mProvider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var fieldname = file.Headers.ContentDisposition.Name; if (fieldname == "pdf_file") { var buffer = await file.ReadAsByteArrayAsync(); string filePath = Path.Combine(taskPath, attached.Name); var saveStream = new MemoryStream(buffer); saveStream.Position = 0; try { using (var fileStream = File.Create(filePath)) { saveStream.CopyTo(fileStream); } } catch { throw; } } else if (fieldname == "txt_file") { //TODO: update metadata of existing attachment var filePath = Path.Combine(taskPath, filename); } } return(Ok()); }