public ActionResult Create(TaskCreateModel model) { if (ModelState.IsValid) { var toAdd = new Task { Name = model.Name, ParentId = model.ParentId }; _taskRepo.Insert(toAdd); try { _taskRepo.Save(); } catch (System.Data.Entity.Infrastructure.DbUpdateException ex) { var msg = ex.InnerException?.InnerException?.Message; if (msg != null && msg.StartsWith("Cannot insert duplicate key row in object 'dbo.Task' with unique index 'IX_ParentId_Name'")) { ModelState.AddModelError("", NameUniquenessMessage); return(View(model)); } throw; } return(RedirectToAction("Index", new { Id = model.ParentId })); } return(View(model)); }
public void Create_Post_ErrorNotHandledText() { // Arrange var taskRepoMock = new Mock <IRepository <Task> >(); var controller = new HomeController(taskRepoMock.Object); var inModel = new TaskCreateModel { ParentId = 1, Name = "a1" }; Task callbackTask = null; taskRepoMock.Setup(r => r.Insert(It.IsAny <Task>())).Callback((Task t) => { callbackTask = t; }); var ex = new Exception("Wrong exception message"); var dbEx = new System.Data.Entity.Infrastructure.DbUpdateException("", new Exception("", ex)); taskRepoMock.Setup(r => r.Save()).Throws(dbEx); // Act Should.Throw <System.Data.Entity.Infrastructure.DbUpdateException>(() => { controller.Create(inModel); }); // Assert taskRepoMock.VerifyAll(); callbackTask.ShouldNotBeNull(); callbackTask.ParentId.ShouldBe(1); callbackTask.Name.ShouldBe("a1"); controller.ModelState.Count.ShouldBe(0); }
private bool ModelIsValid(TaskCreateModel model) { TempData.Remove("fail"); if (model.EffortId <= 0 || model.EffortId == null) { TempData["fail"] = "Please select the effort that is required."; return(false); } ModelState.Remove("EffortDesc"); if (model.ResourceId <= 0 || model.ResourceId == null) { TempData["fail"] = "Please select the resource that is required."; return(false); } ModelState.Remove("ResourceDesc"); if (!ModelState.IsValid) { TempData["fail"] = "Please complete all fields."; return(false); } return(true); }
public ActionResult Create(TaskCreateModel model) { if (!ModelState.IsValid) { return Json(false); } var userId = ReadStorage.Query(new QueryUserIdByEmail(User.Identity.Name)); var createCommand = new CreateTask(model.Title, userId, model.ContextId); _executor.Execute(createCommand); if(model.ParentTaskId != Guid.Empty) { var nestCommand = new NestTask(userId, createCommand.TaskId, model.ParentTaskId); _executor.Execute(nestCommand); } if(model.PrevTaskId != Guid.Empty) { var prioritizeCommand = new PrioritizeTask(userId, createCommand.TaskId, model.PrevTaskId, false, DateTime.UtcNow); _executor.Execute(prioritizeCommand); } return Json(createCommand.TaskId); }
public void Create_Post_Success() { // Arrange var taskRepoMock = new Mock <IRepository <Task> >(); var controller = new HomeController(taskRepoMock.Object); var inModel = new TaskCreateModel { ParentId = 1, Name = "a1" }; Task callbackTask = null; taskRepoMock.Setup(r => r.Insert(It.IsAny <Task>())).Callback((Task t) => { callbackTask = t; }); taskRepoMock.Setup(r => r.Save()).Verifiable(); // Act var rez = controller.Create(inModel); // Assert taskRepoMock.VerifyAll(); callbackTask.ShouldNotBeNull(); callbackTask.ParentId.ShouldBe(1); callbackTask.Name.ShouldBe("a1"); rez.ShouldBeOfType <RedirectToRouteResult>(); var routeResult = (RedirectToRouteResult)rez; routeResult.RouteValues.Count.ShouldBe(2); routeResult.RouteValues["action"].ShouldBe("Index"); routeResult.RouteValues["id"].ShouldBe(1); }
public void Create_Post_ValidationFailed() { // Arrange var taskRepoMock = new Mock <IRepository <Task> >(); var controller = new HomeController(taskRepoMock.Object); var inModel = new TaskCreateModel { ParentId = null, Name = null }; controller.ModelState.AddModelError("", ""); taskRepoMock.Verify(r => r.Save(), Times.Never); // Act var rez = controller.Create(inModel); // Assert rez.ShouldBeOfType <ViewResult>(); var modelTemp = ((ViewResult)rez).Model; modelTemp.ShouldNotBeNull(); modelTemp.ShouldBeOfType <TaskCreateModel>(); var model = (TaskCreateModel)modelTemp; model.ParentId.ShouldBe(null); model.Name.ShouldBe(null); }
public DefaultApiResponse ValidateTask(TaskCreateModel task, string token, out BusinessRulesApiResponse businessRulesApiResponse) { var _data = JsonConvert.SerializeObject(task, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); var _address = ApiHelper.Instance.SiteUrl + ApiHelper.Instance.TaskValidateEndpoint; businessRulesApiResponse = null; try { var _jsonResult = ApiHelper.Instance.WebClient(token).UploadString(_address, "POST", _data); if (_jsonResult == "null") { return(new DefaultApiResponse(200, "OK", new string[] { })); } return(new DefaultApiResponse(500, "Internal Application Error: Fail to Validate Task", new string[] { })); } catch (WebException _webEx) { using StreamReader _r = new StreamReader(_webEx.Response.GetResponseStream()); string _responseContent = _r.ReadToEnd(); return(ApiHelper.Instance.ProcessApiResponseContent(_webEx, _responseContent, out businessRulesApiResponse)); } }
public ActionResult AddTask(TaskCreateModel task) { var Rs = service.Create(task, User.GetUserId()); if (Rs.status == false) { return(BadRequest()); } return(Ok(Rs)); }
public IActionResult CreateTask([FromBody] TaskCreateModel model) { var data = new TaskModel() { UserId = model.UserId, TaskName = model.TaskName, Status = model.Status }; return(Ok(taskService.CreateTask(data))); }
public BllResult TaskAssign([FromBody] TaskCreateModel taskCreateModel) { try { return(AppSession.TaskService.CreateTask(taskCreateModel)); } catch (Exception ex) { return(BllResultFactory.Error($"创建任务失败:{ex.Message}")); } }
public IActionResult Post([FromBody] TaskCreateModel model) { var task = _mapper.Map <Data.Task>(model); try { _taskService.Create(task); return(Ok()); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); } }
private TaskCreateModel GetNewTaskModel(int projectId) { if (clearData) { TempData.Remove("fail"); TempData.Remove("success"); } var model = new TaskCreateModel(); model.ProjectId = projectId; model.StatusId = (int)StatusId.New; return(model); }
public IResponse Create(TaskCreateModel model, int LoggedUser) { var selectedResource = UOW.Users.SingleOrDefault(r => r.Id == model.ResourceId); if (selectedResource == null) { response.status = false; return(response); } var newTask = mapper.Map <ResourceTask>(model); newTask.TaskStateId = 1; newTask.CreatedById = LoggedUser; UOW.Tasks.Add(newTask); UOW.Compelete(); return(response); }
public async Task <IActionResult> CreateTask(TaskCreateModel createModel) { USER user = await _userRepository.GetUserByContext(HttpContext.User); if (_permissionService.CheckPermissionToCreateTasks(user, createModel.TeamId)) { if (ModelState.IsValid) { _taskService.CreateTask(createModel, user); return(RedirectToAction("Index", new { teamId = createModel.TeamId })); } else { return(View(createModel)); } } return(RedirectToAction("AccessDenied", "Account")); }
public async Task <IActionResult> TaskCreate(TaskCreateModel tCM) { if (ModelState.IsValid) { var newZadanie = new UslugaProjekt() { IdProjekt = tCM.projekt.IdProjekt, IdUsluga = tCM.UslugaProjekt.IdUsluga, Opis = tCM.UslugaProjekt.Opis, DataPrzypisaniaZadania = tCM.UslugaProjekt.DataPrzypisaniaZadania, DataZakonczeniaZadania = tCM.UslugaProjekt.DataZakonczeniaZadania, Status = tCM.UslugaProjekt.Status }; _s16693context.Add(newZadanie); await _s16693context.SaveChangesAsync(); return(RedirectToAction("ProjectDetails", new { id = tCM.projekt.IdProjekt })); } else if (!ModelState.IsValid) { var pakiet = await _s16693context.ProjektPakiet.FirstOrDefaultAsync(x => x.IdProjekt == tCM.projekt.IdProjekt && x.DataZakonczeniaWspolpracy == null); var pU = await _s16693context.PakietUsluga.Where(x => x.IdPakiet == pakiet.IdPakiet).Include(u => u.IdUslugaNavigation).ToListAsync(); List <Usluga> uslugas = new List <Usluga>(); foreach (var item in pU) { uslugas.Add(await _s16693context.Usluga.FirstOrDefaultAsync(x => x.IdUsluga == item.IdUsluga)); } var newTCM = new TaskCreateModel { uslugas = uslugas, projekt = tCM.projekt }; return(View("TaskCreate", newTCM)); } return(View(tCM)); }
public ActionResult Create([Bind(Include = "TaskId,SprintId,TaskName,TaskDescription,IsDone")] TaskCreateModel task) { if (ModelState.IsValid) { var newTask = new Task { TaskName = task.TaskName, SprintId = task.SprintId, TaskDescription = task.TaskDescription, IsDone = false }; db.Task.Add(newTask); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.SprintId = new SelectList(db.Sprint, "SprintId", "SprintEnd", task.SprintId); return(View(task)); }
public void CreateTask(TaskCreateModel createModel, USER user) { TEAM team = _teamRepository.GetTeamById(createModel.TeamId); if (team != null) { TASK task = new TASK { TITLE = createModel.Title, TEAM = team, USER = user, CREATE_TIME = DateTime.Now, DEATHLINE = createModel.Deathline, START_TIME = createModel.StartTime, DESCRIPTION = createModel.Description, END_TIME = createModel.EndTime, TASK_STATUS = _taskRepository.GetTaskStatusesByTeam(team).FirstOrDefault(x => x.PREV_STATUS == null) }; _taskRepository.CreateTask(task); } }
public void Create_Post_ErrorNotHandledType() { // Arrange var taskRepoMock = new Mock <IRepository <Task> >(); var controller = new HomeController(taskRepoMock.Object); var inModel = new TaskCreateModel { ParentId = 1, Name = "a1" }; Task callbackTask = null; taskRepoMock.Setup(r => r.Insert(It.IsAny <Task>())).Callback((Task t) => { callbackTask = t; }); taskRepoMock.Setup(r => r.Save()).Throws(new NotSupportedException()); // Act Should.Throw <NotSupportedException>(() => { controller.Create(inModel); }); // Assert taskRepoMock.VerifyAll(); callbackTask.ShouldNotBeNull(); callbackTask.ParentId.ShouldBe(1); callbackTask.Name.ShouldBe("a1"); controller.ModelState.Count.ShouldBe(0); }
public async Task <IActionResult> Create(TaskCreateModel model) { try { if (ModelState.IsValid) { var newTaskId = await _mediator.Send(new CreateTaskCommand() { Name = model.Name, Priority = model.Priority, Statues = "NotStarted" }); return(RedirectToAction("Index")); } } catch (AppException ex) { ModelState.AddModelError("app_error", ex.Message); } return(View(model)); }
public async Task <IActionResult> TaskCreate(int?id) { var pakiet = await _s16693context.ProjektPakiet.FirstOrDefaultAsync(x => x.IdProjekt == id && x.DataZakonczeniaWspolpracy == null); var pU = await _s16693context.PakietUsluga.Where(x => x.IdPakiet == pakiet.IdPakiet).Include(u => u.IdUslugaNavigation).ToListAsync(); List <Usluga> uslugas = new List <Usluga>(); foreach (var item in pU) { uslugas.Add(await _s16693context.Usluga.FirstOrDefaultAsync(x => x.IdUsluga == item.IdUsluga)); } var projekt = await _s16693context.Projekt.FindAsync(id); var tCM = new TaskCreateModel { uslugas = uslugas, projekt = projekt }; return(View(tCM)); }
public void Create_Post_ErrorHandled() { // Arrange var taskRepoMock = new Mock <IRepository <Task> >(); var controller = new HomeController(taskRepoMock.Object); var inModel = new TaskCreateModel { ParentId = 1, Name = "a1" }; Task callbackTask = null; taskRepoMock.Setup(r => r.Insert(It.IsAny <Task>())).Callback((Task t) => { callbackTask = t; }); var ex = new Exception("Cannot insert duplicate key row in object 'dbo.Task' with unique index 'IX_ParentId_Name'"); var dbEx = new System.Data.Entity.Infrastructure.DbUpdateException("", new Exception("", ex)); taskRepoMock.Setup(r => r.Save()).Throws(dbEx); // Act var rez = controller.Create(inModel); // Assert taskRepoMock.VerifyAll(); callbackTask.ShouldNotBeNull(); callbackTask.ParentId.ShouldBe(1); callbackTask.Name.ShouldBe("a1"); controller.ModelState.Count.ShouldBe(1); controller.ModelState[""].Errors.Single().ErrorMessage.ShouldBe("Task name should be unique on this nesting level"); rez.ShouldBeOfType <ViewResult>(); var modelTemp = ((ViewResult)rez).Model; modelTemp.ShouldNotBeNull(); modelTemp.ShouldBeOfType <TaskCreateModel>(); var model = (TaskCreateModel)modelTemp; model.ParentId.ShouldBe(1); model.Name.ShouldBe("a1"); }
private void WorkerFetcherDoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { if (dataGridView_task != null && dataGridView_task.RowCount > 1) { _errorRowCount = 0; //while validating, deactivate other buttons Invoke((MethodInvoker)(() => button_validate.Enabled = false)); Invoke((MethodInvoker)(() => button_import.Enabled = false)); Invoke((MethodInvoker)(() => button_clear.Enabled = false)); Invoke((MethodInvoker)(() => button_taskSelectFile.Enabled = false)); Invoke((MethodInvoker)(() => textBox_taskImportMessages.AppendText("Start time: " + DateTime.Now))); try { foreach (DataGridViewRow _row in dataGridView_task.Rows) { if (WorkerFetcher.CancellationPending) { break; } _isMappingFieldValueToIDCorrect = true; _isFirstTimeInvalidMapping = true; if (_row.DataBoundItem != null) { TaskCreateModel _newTask = new TaskCreateModel { ProjectID = (int)MapFieldValueToID(ProjectNo, _row, false), TaskNo = TaskHandler.Instance.CheckAndGetString(dataGridView_task, TaskNo, _row), TaskName = TaskHandler.Instance.CheckAndGetString(dataGridView_task, TaskName, _row), Description = TaskHandler.Instance.CheckAndGetString(dataGridView_task, Description, _row), StartDate = TaskHandler.Instance.CheckAndGetDate(dataGridView_task, StartDate, _row), EndDate = TaskHandler.Instance.CheckAndGetDate(dataGridView_task, EndDate, _row), AdditionalTextIsRequired = TaskHandler.Instance.CheckAndGetBoolean(dataGridView_task, AdditionalTextIsRequired, _row), BudgetHours = TaskHandler.Instance.CheckAndGetDouble(dataGridView_task, BudgetHours, _row), BudgetAmount = TaskHandler.Instance.CheckAndGetDouble(dataGridView_task, BudgetAmount, _row), ProjectSubContractID = (int)MapFieldValueToID(ContractName, _row, false), IsReadyForInvoicing = TaskHandler.Instance.CheckAndGetBoolean(dataGridView_task, IsReadyForInvoicing, _row), TaskTypeID = MapFieldValueToID(TaskType, _row, true), HourlyRateID = MapFieldValueToID(ContractHourlyRate, _row, true), ParentTaskID = MapFieldValueToID(ParentTaskNo, _row, true), IsBillable = TaskHandler.Instance.CheckAndGetBoolean(dataGridView_task, IsBillable, _row), PaymentRecognitionModel = (PaymentRecognitionModelTypes)(int)MapFieldValueToID(PaymentRecognitionModel, _row, false), PaymentAmount = TaskHandler.Instance.CheckAndGetDouble(dataGridView_task, PaymentAmount, _row), TaskHourlyRate = TaskHandler.Instance.CheckAndGetDouble(dataGridView_task, TaskHourlyRate, _row), PaymentProductNo = TaskHandler.Instance.CheckAndGetString(dataGridView_task, PaymentProductNo, _row), PaymentName = TaskHandler.Instance.CheckAndGetString(dataGridView_task, PaymentName, _row), PaymentInvoiceDate = TaskHandler.Instance.CheckAndGetNullableDate(dataGridView_task, PaymentInvoiceDate, _row) }; if (_isMappingFieldValueToIDCorrect) { if (_senderButton.Name == button_validate.Name) { var _defaultApiResponse = TaskHandler.Instance.ValidateTask(_newTask, AuthenticationHandler.Instance.Token, out var _businessRulesApiResponse); _errorRowCount = ApiHelper.Instance.HandleApiResponse(_defaultApiResponse, _row, _businessRulesApiResponse, textBox_taskImportMessages, _errorRowCount, WorkerFetcher, this); } else { var _defaultApiResponse = TaskHandler.Instance.ImportTask(_newTask, AuthenticationHandler.Instance.Token, out var _businessRulesApiResponse); _errorRowCount = ApiHelper.Instance.HandleApiResponse(_defaultApiResponse, _row, _businessRulesApiResponse, textBox_taskImportMessages, _errorRowCount, WorkerFetcher, this); } } } } TaskHandler.Instance.DisplayErrorRowCountAndSuccessMessage(_errorRowCount, button_import, button_validate, _senderButton, textBox_taskImportMessages, this); } catch (FormatException _ex) { MessageBox.Show(_ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception _ex) { MessageBox.Show(_ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } //reactivate buttons after work is done Invoke((MethodInvoker)(() => button_validate.Enabled = true)); Invoke((MethodInvoker)(() => button_clear.Enabled = true)); Invoke((MethodInvoker)(() => button_taskSelectFile.Enabled = true)); } }
public ActionResult Create(TaskCreateModel model) { TaskService.Create(model.Name, model.ProjectId, model.UserId); return(RedirectToAction("View", "Project", new { @id = model.ProjectId })); }
public async Task <TaskCreateModel> AssignLookUps(IQueryable <Project> projects, TaskCreateModel model) { LookUp lookups = null; try { lookups = await _cacheHelper.CheckLookupCache(_cache); } catch (Exception ex) { var error = ex; } model.EffortDesc = lookups.Efforts; model.ResourceDesc = lookups.Resources; model.StatusDesc = lookups.Statuses; model.ProjectName = projects .Select(y => new SelectListItem { Value = y.Id.ToString(), Text = $"{y.Description}" }); return(model); }
public IActionResult Edit(int id, [Bind("Id,ProjectId,Name,Description,EffortId,ResourceId,StatusId,Files")] TaskCreateModel viewModel) { if (id != viewModel.Id) { return(NotFound()); } try { if (!ModelIsValid(viewModel)) { this.AssignLookUps(_projectInteractor.GetProjectName(viewModel.ProjectId), viewModel); return(View(viewModel)); } var model = new TaskPT() { Id = viewModel.Id, ProjectId = viewModel.ProjectId, Name = viewModel.Name, Description = viewModel.Description?.TruncateAndTrim(255), EffortId = (int)viewModel.EffortId, StatusId = viewModel.StatusId, ResourceId = (int)viewModel.ResourceId }; //Save files to database var documents = new List <Documents>(); if (viewModel.Files.Count() > 0) { foreach (IFormFile item in viewModel.Files) { if (item.Length > 0) { string fileName = Path.GetFileName(item.FileName); string fileType = Path.GetExtension(item.FileName); documents.Add(new Documents() { FileName = fileName, FileType = fileType, Task = model, TaskId = viewModel.Id, }); } } //link documents to model model.Documents = documents; } var result = _interactor.UpdateTask(id, model); if (result.Item1 == true) { var files = _fileUpload.UploadDocuments(viewModel.Files, viewModel.ProjectId).Result; TempData["success"] = $"'{viewModel.Name}' was updated!"; return(RedirectToAction("Index", "Task", new { id = viewModel.ProjectId })); } TempData.Remove("fail"); TempData["fail"] = $"Error: {result.Item2}"; return(View()); } catch (Exception ex) { TempData["fail"] = $"Error: {ex.Message}"; return(View()); } }
public ActionResult <bool> CreateTask([FromBody] TaskCreateModel value) { return(_tasksManager.CreateTask(value.Name, value.Description, value.ShortDescription, value.Tests, value.Results, path)); }