public async Task <IActionResult> UpdateTask(int id, int userId, TaskDto taskDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var taskFromRepo = await _repo.GetTask(id); taskDto.Id = taskFromRepo.Id; _mapper.Map(taskDto, taskFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating task {id} failed on save"); }
public async Task UpdateATask() { var tempTask = new TaskDto() { Name = nameof(UpdateATask) }; await _createTaskCommand.ExecuteAsync(tempTask); var result = await _getTaskQuery.ExecuteAsync(x => x.Name == tempTask.Name); var task = result.First(); task.Name += " updated"; tempTask = _mapper.Map <TaskDto>(task); await _sut.ExecuteAsync(tempTask); }
public async Task <IActionResult> Update([FromBody] TaskDto task, int id) { if (task == null) { return(this.BadRequest()); } this._logger.LogDebug($"PUT api/tasks/{id}"); task.Id = id; var result = await this._taskService.Update(task); if (result == null) { return(this.NotFound()); } return(this.Ok(result)); }
public async Task <TaskDto> AddAsync(TaskDto taskDto, CancellationToken cancellationToken) { var validacao = _validator.Validate(taskDto); if (!validacao.IsValid) { throw new Exception(validacao.Errors.First().ErrorMessage); } var task = _mapper.Map <Domain.Task>(taskDto); await Task.Run(() => { _tasklistDbContext.Tasks.AddAsync(task); _tasklistDbContext.SaveChangesAsync(); }, cancellationToken); return(taskDto); }
public MappingHelper(TaskDto dto) { this.actions = new Dictionary <string, Action <string> >() { { "A", s => dto.Name = s }, { "B", s => dto.Date = s }, { "C", s => dto.DueDate = s }, { "D", s => dto.DurationInSeconds = s }, { "E", s => dto.Location.Street = s }, { "F", s => dto.Location.Door = s }, { "G", s => dto.Location.Floor = s }, { "H", s => dto.Location.ZipCode = s }, { "I", s => dto.Location.City = s }, { "J", s => dto.Location.Country = s }, { "K", s => dto.Location.Alias = s }, { "L", s => dto.Location.Tags = s != null?s.Split("|") : Array.Empty <string>() }, { "M", s => dto.Notes = s } }; }
public async Task <int> Create(TaskDto request) { using (var conn = new SqlConnection(_connectionString)) { if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } DynamicParameters pars = new DynamicParameters(); pars.Add("@ID", request.ID, DbType.Int32, direction: ParameterDirection.Input); pars.Add("@Name", request.Name, DbType.String, direction: ParameterDirection.Input); pars.Add("@StartDate", request.StartDate, DbType.Date, direction: ParameterDirection.Input); pars.Add("@EndDate", request.EndDate, DbType.Date, direction: ParameterDirection.Input); pars.Add("@Status", request.Status, DbType.Int32, direction: ParameterDirection.Input); var result = await conn.ExecuteAsync("CreateOrUpdateTask", pars, commandType : CommandType.StoredProcedure); return(result); } }
public void UpdateDto(ICollection <ActivityDto> dtos, IEnumerable <WActivity> activities) { if (dtos == null || activities == null) { return; } foreach (var activity in activities) { if (!dtos.Any(x => x.Id == activity.Id)) { var activityDto = new ActivityDto(); _conversionService.ConvertToDto(activityDto, activity); var taskDto = new TaskDto(); _conversionService.ConvertToDto(taskDto, activity.WTask); activityDto.Task = taskDto; dtos.Add(activityDto); } } }
/// <summary> /// Update the status of a task to In Progress or Done. /// </summary> /// <param name="taskId"></param> /// <param name="taskToUpdate"></param> /// <returns></returns> public async Task <int> UpdateStatus(int taskId, TaskDto taskToUpdate) { try { if (taskToUpdate.Status != "Done") { Entities.Task taskToDelete = new Entities.Task() { TaskId = taskId, Status = taskToUpdate.Status }; using (var context = new WorkFlowContext()) { context.Task.Attach(taskToDelete); context.Entry(taskToDelete).Property(t => t.Status).IsModified = true; return(await context.SaveChangesAsync()); } } else { using (var context = new WorkFlowContext()) { Entities.Task taskToUpdateFromDb = await context.Task.FindAsync(taskId); if (taskToUpdateFromDb != null) { taskToUpdateFromDb.Status = taskToUpdate.Status; taskToUpdateFromDb.ActualCompletionDate = taskToUpdate.ActualCompletionDate; return(await context.SaveChangesAsync()); } else { return(0); } } } } catch (Exception ex) { throw ex; } }
public IActionResult ChangeTask(int id, [FromBody] TasksEditModel model) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } TaskDto taskDto = new TaskDto() { Description = model.Description, DueDate = model.DueDate, Title = model.Title, UserId = model.UserId, Status = model.Status, DateModified = DateTime.Now }; return(Ok(new NSIResponse <TaskDto> { Data = _taskRepository.EditTask(id, taskDto), Message = "Success" })); } catch (NSIException ex) { Logger.Logger.LogError(ex); if (ex.ErrorType == DC.Exceptions.Enums.ErrorType.MissingData) { return(NoContent()); } return(BadRequest(new NSIResponse <object> { Data = null, Message = "Parameter error!" })); } catch (Exception ex) { Logger.Logger.LogError(ex); return(StatusCode(500, new NSIResponse <object> { Data = null, Message = ex.Message })); } }
public bool AddFavorites(FavoritesMobileDto favoritesMobileDto) { TaskDto tmpTask = null; try { try { tmpTask = _taskRepositories.Get(favoritesMobileDto.Task.Name); } catch (Exception e) { } if (tmpTask == null) { tmpTask = new TaskDto() { Description = "", Name = favoritesMobileDto.Task.Name, Activities = new List <ActivityDto>(), Favorites = new List <FavoritesDto>(), Type = "" }; _taskRepositories.Add(tmpTask); } var fav = new FavoritesDto() { Task = _taskRepositories.Get(tmpTask.Name), User = _userRepositories.Get(favoritesMobileDto.UserEmail) }; _favoritesRepositories.Add(fav); } catch (Exception e) { return(false); } return(true); }
public IHttpActionResult EditTask(int id, TaskDto taskDto) { var userID = User.Identity.GetUserId(); Completed completed = new Completed(); To_Do to_Do = new To_Do(); using (var dc = new ProgressTrackerEntities()) { var updatedTask = (Milestone)taskDto; updatedTask.Id = id; if (taskDto.progress == 1) { updatedTask.Status = "Completed"; completed.Progress = updatedTask.Progress; completed.StudentNumber = updatedTask.StudentNumber; dc.Completeds.Add(completed); dc.SaveChanges(); } else if (taskDto.progress == 0) { updatedTask.Status = "To-Do"; to_Do.StudentNumber = updatedTask.StudentNumber; to_Do.Progress = updatedTask.Progress; dc.To_Do.Add(to_Do); dc.SaveChanges(); } else { updatedTask.Status = "In-Progress"; } dc.Entry(updatedTask).State = EntityState.Modified; dc.SaveChanges(); return(Ok(new { action = "updated" })); } }
public void getAllTasks() { int id = 21; string description = "Test"; DateTime dueDate = DateTime.Now; String title = "Test Task"; var Task = new List <TaskDto>() { new TaskDto() { TaskId = 1 } }; NSI.REST.Models.TasksCreateModel task = new TasksCreateModel() { TaskId = id, Description = description, DueDate = dueDate, Title = title }; var task2 = new TaskDto { TaskId = id, Description = description, DueDate = dueDate, Title = title }; var taskRepo = new Mock <ITaskRepository>(); taskRepo.Setup(x => x.CreateTask(task2)); var taskManipulation = new TaskManipulation(taskRepo.Object); var controller = new TasksController(taskManipulation); var result = controller.GetTasks(21, 1); Assert.IsType <OkObjectResult>(result); }
public void getTasksByUserId_ReturnOK() { int id = 21; string description = "Test"; DateTime dueDate = DateTime.Now; String title = "Test Task"; var userOnTask = new List <TaskDto>() { new TaskDto() { UserId = 69 } }; NSI.REST.Models.TasksCreateModel task = new TasksCreateModel() { TaskId = id, Description = description, DueDate = dueDate, Title = title, UserId = 69 }; var task2 = new TaskDto { TaskId = id, Description = description, DueDate = dueDate, Title = title, UserId = 69 }; var logger = new Mock <Microsoft.Extensions.Logging.ILogger <TasksController> >().Object; var taskMan = new Mock <ITaskManipulation>(); var controller = new TasksController(taskMan.Object); var result = controller.GetTasksByUserId(69, 3, 1); Xunit.Assert.IsType <OkObjectResult>(result); }
private async Task <Tuple <HttpResponseMessage, TaskDto> > CreateTask(HttpClient client) { var create = await ProjectsControllerTest.CreateProject(client); var dto = new TaskDto() { Name = "The name", Contact = "The contact", Manager = "The manager", DueDate = DateTime.Now.AddDays(25), State = Enums.State.TO_DO, ProjectId = create.Item2.Id }; var response = await client.PostAsJsonAsync($"{ProjectUrl}/{create.Item2.Id}/tasks", dto); dto = await response.Content.ReadAsAsync <TaskDto>(); return(new Tuple <HttpResponseMessage, TaskDto>(response, dto)); }
public async Task SaveTask([FromBody] TaskDto task) { //await Task.Delay(TimeSpan.FromSeconds(2)); try { TaskBo taskBo = _mapper.Map <TaskBo>(task); await _taskService.SaveTaskAsync(taskBo); } catch (DbUpdateException e) { } catch (Exception e) { } BoardDto boardDto = await GetBoardAsync(); await _hubContext.Clients.All.RefreshBoard(boardDto); }
public IHttpActionResult UpdateTask([FromBody] TaskDto dto) { try { var taskExists = _taskService.GetTaskById(dto.Id); if (taskExists == null) { return(NotFound()); } return(Ok(_taskService.UpdateTask(dto))); } catch (Exception ex) { //LOG //return StatusCode(HttpStatusCode.InternalServerError); return(InternalServerError(new Exception("An unexpected error occured! Please try again later!"))); } }
public void UpdateTask(TaskDto taskDto) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var taskInDb = _context.Tasks.SingleOrDefault(c => c.Id == taskDto.Id); if (taskInDb == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } Mapper.Map(taskDto, taskInDb); _context.SaveChanges(); }
public async Task <int> CreateTask(TaskDto newTask, string token) { var stringContent = new StringContent(JsonSerializer.Serialize(newTask), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync($"{ServerInfo.Url}/api/tasks?token={WebUtility.UrlEncode(token)}", stringContent); var body = await response.Content.ReadAsStringAsync(); switch (response.StatusCode) { case HttpStatusCode.Created: break; case HttpStatusCode.NotAcceptable: throw new NotAcceptableException(body); case HttpStatusCode.Unauthorized: throw new NotAuthenticatedException(body); } return(JsonSerializer.Deserialize <int>(body)); }
private void ChangeTask(TaskDto task) { try { bool?result = _controller.GetConfigs <TaskCardView, TaskCardViewModel>() .View(v => v.Icon = _imageManager.GetImage(ImageType.TaskImage)) .AdditionalViewModelParams(task) .RunDialog(); if (result == true) { task.Organization = null; _dataProxy.UpdateItems(task); } } catch (Exception ex) { MessageService.ShowError(ex.Message); } }
/// <summary> /// Creates a todo. UserId is taken from the model. /// </summary> /// <param name="task">The todo to create.</param> public void CreateTask(TaskDto task) { if (!ReferenceEquals(task.Name, null)) { //User firstUser = new User { Name = "Zheldak", BirthDay = new DateTime(1995, 03, 05) }; //User firstElasticUser = new User { Name = "Zheldak", BirthDay = new DateTime(1995, 03, 05) }; //_userRepository.Create(firstUser); //firstElasticUser.Id = 1; //_userElasticRepository.Create(firstElasticUser); User user = _unitOfWork.Users.GetById(1); task.CreatedDate = DateTime.Now; ToDoDataAccess.Entities.NHibernate.Task newTask = _mapper.Map <ToDoDataAccess.Entities.NHibernate.Task>(task); newTask.User = user; _unitOfWork.Tasks.Create(newTask); Task elasticTask = _mapper.Map <Task>(newTask); _unitOfWorkElastic.Tasks.Create(elasticTask); } }
/// <summary> /// Create a new task. /// </summary> /// <param name="taskToCreate"></param> /// <returns></returns> public async Task <int> Create(TaskDto taskToCreate) { try { if (taskToCreate != null) { Entities.Task taskEntityToCreate = Mapper.Map <Entities.Task>(taskToCreate); using (var context = new WorkFlowContext()) { context.Task.Add(taskEntityToCreate); return(await context.SaveChangesAsync()); } } return(0); } catch (Exception ex) { throw ex; } }
public Result <TaskDto> Create(TaskDto model) { if (model != null) { try { var task = _mapper.Map <TaskDto, Taskk>(model); task.CreatedDate = DateTime.Now; task.IsDeleted = true; _unitOfWork.taskRepository.Add(task); _unitOfWork.Save(); return(new Result <TaskDto>(true, $"{model.Name} adlı görev başarı ile eklenmiştir")); } catch (Exception ex) { return(new Result <TaskDto>(false, "Kayıt Gerçekleştirilirken Hata Oluştu" + ex.Message.ToString())); } } return(new Result <TaskDto>(false, "Parametre Olarak Geçilen Data Boş Olamaz")); }
public void CheckProjectTasksSaving() { Random rand = new Random(); bool exist = false; var task = new TaskDto() { CreateDate = DateTime.Now, TaskName = "example", FinishDate = DateTime.Now, UserId = rand.Next(1, 5), ProjectId = rand.Next(1, 5), KanbanId = rand.Next(1, 5) }; if (task is TaskDto && task != null) { exist = true; } Assert.IsTrue(exist); }
public HttpResponseMessage Put(TaskDto dto) { try { if (dto != null) { TaskRepository.Update(dto); return(Request.CreateResponse(HttpStatusCode.OK)); } return(Request.CreateResponse(HttpStatusCode.BadRequest)); } catch (ElementNotFoundException e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } catch (Exception) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Generic error happened.")); } }
public IHttpActionResult EditTask(int id, TaskDto taskDto) { var updatedTask = (Task)taskDto; updatedTask.Id = id; if (!string.IsNullOrEmpty(taskDto.target)) { // reordering occurred this._UpdateOrders(updatedTask, taskDto.target); } db.Entry(updatedTask).State = EntityState.Modified; db.SaveChanges(); return(Ok(new { action = "updated" })); }
public IActionResult Update(TaskDto model) { if (ModelState.IsValid) { var data = _taskBusiness.Update(model); if (data.IsSuccess) { _toastNotification.AddSuccessToastMessage(data.Message, new ToastrOptions { Title = "Başarılı İşlem" }); return(RedirectToAction("Index")); } return(View(model)); } else { return(View(model)); } }
public static TaskDto Map(Task entity) { var dto = new TaskDto(); dto.Id = entity.Id; dto.Description = entity.Description; dto.AssignedTo = entity.AssignedTo != null?UserDtoMapper.Map(entity.AssignedTo) : null; dto.Type = entity.Type != null?TaskTypeDtoMapper.Map(entity.Type) : null; dto.DueDate = entity.DueDate; dto.Status = entity.Status; dto.RagStatus = entity.RagStatus; dto.CreatedOn = entity.CreatedOn; dto.LastModifiedOn = entity.LastModifiedOn; dto.Deleted = entity.Deleted; //todo: don't do LastModifiedBy in here, have a 'MapWithLastModifiedBy' method - otherwise infinately recursive call. //todo: don't do CreatedBy in here, have a 'MapWithCreatedBy' method - otherwise infinately recursive call. return(dto); }
public async Task <IEnumerable <TaskDto> > GetTasksNotInPlanAsync(int planId) { var plan = await db.Plans.Get(planId); if (plan == null) { return(null); } IEnumerable <TaskEntity> tasksNotUsedInPlan = await db.Tasks.GetTasksNotInPlanAsync(planId); if (tasksNotUsedInPlan == null) { return(null); } var tasksNotUsedInPlanList = new List <TaskDto>(); foreach (var task in tasksNotUsedInPlan) { var taskDto = new TaskDto ( task.Id, task.Name, task.Description, task.Private, task.Create_Id, await db.Users.ExtractFullNameAsync(task.Create_Id), task.Mod_Id, await db.Users.ExtractFullNameAsync(task.Mod_Id), task.Create_Date, task.Mod_Date, null, null, null); if (!tasksNotUsedInPlanList.Contains(taskDto)) { tasksNotUsedInPlanList.Add(taskDto); } } return(tasksNotUsedInPlanList); }
public async Task UpdatePriorityAsync_ValidData_Successful() { // Arrange. var taskEntityToSeed = TaskEntityToSeed; Seed(TripFlipDbContext, ValidUser); Seed(TripFlipDbContext, TripEntityToSeed); Seed(TripFlipDbContext, RouteEntityToSeed); Seed(TripFlipDbContext, TaskListEntityToSeed); Seed(TripFlipDbContext, taskEntityToSeed); Seed(TripFlipDbContext, TripSubscriberEntitiesToSeed); Seed(TripFlipDbContext, RouteSubscriberEntitiesToSeed); Seed(TripFlipDbContext, RouteRoleEntitiesToSeed); Seed(TripFlipDbContext, RouteSubscriberEditorRoleEntityToSeed); CurrentUserService = CreateCurrentUserService(ValidUser.Id, ValidUser.Email); var updateTaskPriorityDto = GetUpdateTaskPriorityDto(); var taskService = new TaskService(TripFlipDbContext, Mapper, CurrentUserService); var expectedTaskDto = new TaskDto() { Id = updateTaskPriorityDto.Id, PriorityLevel = updateTaskPriorityDto.PriorityLevel, Description = taskEntityToSeed.Description, IsCompleted = taskEntityToSeed.IsCompleted, TaskListId = taskEntityToSeed.TaskListId }; var taskDtoComparer = new TaskDtoComparer(); // Act. var resultTaskDto = await taskService.UpdatePriorityAsync(updateTaskPriorityDto); // Assert. Assert.AreEqual(0, taskDtoComparer.Compare(expectedTaskDto, resultTaskDto)); }
public void AddCategoryAction() { int id = Categories.Last().Id + 1; var newCategory = new CategoryDto { Id = id, Name = NewCategory.Name, Description = NewCategory.Description, StateType = NewCategory.StateType }; RestClient.AddCategory(newCategory); Categories.Add(newCategory); NavigationViewItems.AddMenuItem(newCategory); int taskId = AllTasks.Last().Id + 1; var newTask = new TaskDto { Id = taskId, Name = "TO-DO 1", Description = "", State = 0, DeadlineDate = DateTime.Now, ScheduledDate = DateTime.Now, ParentId = newCategory.Id }; RestClient.AddTask(newTask); AllTasks.Add(newTask); Categories.Where(n => n.Id == newCategory.Id).First().Tasks.Add(newTask); taskId = AllTasks.Last().Id + 1; newTask = new TaskDto { Id = taskId, Name = "TO-DO 2", Description = "", State = 0, DeadlineDate = DateTime.Now, ScheduledDate = DateTime.Now, ParentId = newCategory.Id }; RestClient.AddTask(newTask); AllTasks.Add(newTask); Categories.Where(n => n.Id == newCategory.Id).First().Tasks.Add(newTask); taskId = AllTasks.Last().Id + 1; newTask = new TaskDto { Id = taskId, Name = "TO-DO 3", Description = "", State = 0, DeadlineDate = DateTime.Now, ScheduledDate = DateTime.Now, ParentId = newCategory.Id }; RestClient.AddTask(newTask); AllTasks.Add(newTask); Categories.Where(n => n.Id == newCategory.Id).First().Tasks.Add(newTask); NewCategory.Name = String.Empty; NewCategory.Description = String.Empty; }
public IEnumerable<DynamicFieldDto> SaveFields(IEnumerable<DynamicFieldDto> fieldDtos, TaskDto taskDto) { var document = _repository.Query<Document>().SingleOrDefault(x => x.Id == taskDto.CurrentDocument.Id); if (document == null) { throw new ArgumentException("Task should have this document"); } var fieldToReturn = new List<DynamicField>(); foreach (var dynamicFieldDto in fieldDtos) { if (dynamicFieldDto.Id == Guid.Empty) { var newField = new DynamicField { Configuration = _repository.Query<DynamicFieldTemplate>().FirstOrDefault(x => x.Id == dynamicFieldDto.Configuration.Id) }; var newFieldValue = dynamicFieldDto.GetValue(); if (newFieldValue != null) { newField.SetValue(newFieldValue); document.Fields.Add(newField); } else { newField.Id = Guid.Empty; } fieldToReturn.Add(newField); } else { var dynamicFieldToUpdate = _repository.Query<DynamicField>().FirstOrDefault(x => x.Id == dynamicFieldDto.Id); if (dynamicFieldToUpdate == null) throw new ArgumentException("Field to update is not found"); var newFieldValue = dynamicFieldDto.GetValue(); dynamicFieldToUpdate.SetValue(newFieldValue); fieldToReturn.Add(dynamicFieldToUpdate); } } _repository.Commit(); var result = new List<DynamicFieldDto>(); foreach (var dynamicField in fieldToReturn) { var dynamicFieldDto = new DynamicFieldDto { Id = dynamicField.Id, Configuration = new DynamicFieldTemplateDto { Id = dynamicField.Configuration.Id, Code = dynamicField.Configuration.Code, IsEnabled = dynamicField.Configuration.IsEnabled, Label = dynamicField.Configuration.Label, Length = dynamicField.Configuration.Length, Type = dynamicField.Configuration.Type } }; dynamicFieldDto.CreateValue(); dynamicFieldDto.Value.Id = dynamicField.Value.Id; var newValue = dynamicField.GetValue(); if (newValue != null) dynamicFieldDto.SetValue(newValue); result.Add(dynamicFieldDto); } return result; }
/// <summary> /// Test events of the task. /// </summary> /// <param name="task">Task to test.</param> /// <returns>True if event can be triggered, else false.</returns> private static bool CanTrigger(TaskDto task) { return task.Events.Select(AEventBusiness.GetBusiness) .Aggregate(false, (current, business) => current | business.Test()); }