private List <FilterDefinition <TodoDTO> > SetFilterQuery(TodoDTO parameters) { var filters = new List <FilterDefinition <TodoDTO> >(); if (parameters.Description != null && !parameters.Description.Equals("")) { var filter = Builders <TodoDTO> .Filter.Regex("Description", new BsonRegularExpression(parameters.Description, "i")); filters.Add(filter); } if (parameters._id != null && !parameters._id.Equals("")) { var filter = Builders <TodoDTO> .Filter.Regex("_id", new BsonRegularExpression(parameters._id, "i")); filters.Add(filter); } if (parameters.Status != null && !parameters.Status.Equals("")) { var filter = Builders <TodoDTO> .Filter.Eq("Status", parameters.Status); filters.Add(filter); } return(filters); }
/// <summary> /// Inserir tarefa /// </summary> /// <param name="registro">Registro da tarefa a ser inserida</param> public TodoDTO Post(TodoDTO registro) { try { if (registro.Id > 0) { throw new Exception("Registo não pode conter ID preenchido!"); } var resultado = new TodoItem() { Done = registro.Done, CriadoEm = DateTime.Now, Todo = registro.Todo }; DbContext.Listas.Add(resultado); DbContext.SaveChanges(); return(new TodoDTO() { CriadoEm = resultado.CriadoEm, Done = resultado.Done, Id = resultado.Id, Todo = resultado.Todo }); } catch (Exception) { throw; } }
public IEnumerable <TodoDTO> GetAll() { var parameters = new List <SqlParameter>(); var dataReader = sqlHelper.GetDataReader("sp_GetAllTodo", CommandType.StoredProcedure, null, out connection); try { var todos = new List <TodoDTO>(); while (dataReader.Read()) { var todo = new TodoDTO(); todo.Title = Convert.ToString(dataReader["Title"]); todo.Complete = Convert.ToBoolean(dataReader["Complete"]); todo.Id = Convert.ToInt32(dataReader["Id"]); todos.Add(todo); } return(todos); } catch (Exception ex) { throw ex; } finally { dataReader.Close(); CloseConnection(); } }
public async Task <TodoReadDTO> AddTodo(TodoDTO todo) { _logger.LogInformation("Call to AddTodo function made"); using (var session = await _client.StartSessionAsync()) { try { session.StartTransaction(); var model = _mapper.Map <TodoModel>(todo); this.Todos.InsertOne(session, model); await session.CommitTransactionAsync(); var modelDTO = this._mapper.Map <TodoReadDTO>(model); _logger.LogInformation("Call to AddTodo function completed."); return(modelDTO); } catch (Exception ex) { _logger.LogInformation("Call to AddTodo function was terminate."); await session.AbortTransactionAsync(); throw ex; } } }
public async Task <TodoDTO> SaveAsync(TodoDTO dto = null, Todo_Master entity = null) { if (dto == null && entity == null) { throw new Exception($"{nameof(dto)} and {nameof(entity)} they were both null."); } if (dto != null && entity == null) { if (dto.TD_ID > 0) { entity = await FindAsync(todoId : dto.TD_ID); } entity ??= new Todo_Master(); _mapper.Map(dto, entity); } if (dto?.TD_ID <= 0 || entity.TD_ID <= 0) { entity = await _repository.AddAsync(entity); } else { entity = await _repository.UpdateAsync(entity); } await _repository.UnitOfWork.SaveEntitiesAsync(); dto ??= new TodoDTO(); _mapper.Map(entity, dto); return(dto); }
public async Task FindByIdAsync_MakesCorrectCallsAndReturnsCorrectObject() { // Arrange var expectedPrimaryKeyId = 1; var expectedTodoDTO = new TodoDTO() { Id = expectedPrimaryKeyId, Name = "Test Todo", IsComplete = true }; var todo = new Todo(); var mockedRepository = new Mock <ITodosRepository>(); var mockedMapper = new Mock <IMapper>(); mockedRepository.Setup(r => r.FindByIdAsync(expectedPrimaryKeyId)).ReturnsAsync(todo); mockedMapper.Setup(m => m.Map <Todo, TodoDTO>(todo)).Returns(expectedTodoDTO); var service = new TodosService(mockedMapper.Object, mockedRepository.Object); // Action var actualTodoDTO = await service.FindByIdAsync(expectedPrimaryKeyId); // Assert Assert.NotNull(actualTodoDTO); Assert.Equal(expectedTodoDTO, actualTodoDTO); mockedRepository.Verify(r => r.FindByIdAsync(expectedPrimaryKeyId), Times.Once()); mockedMapper.Verify(m => m.Map <Todo, TodoDTO>(todo), Times.Once()); }
public async Task CreateTodoAsync_MakesCorrectCallsAndReturnsUpdatedTodoWithId() { // Arrange var expectedCreatedTodoDTO = new CreatedTodoDTO() { Name = "Test Todo", IsComplete = true }; var expectedTodoDTO = new TodoDTO() { Name = expectedCreatedTodoDTO.Name, IsComplete = expectedCreatedTodoDTO.IsComplete.Value }; var expectedPrimaryKeyId = 1; var todo = new Todo(); var mockedMapper = new Mock <IMapper>(); var mockedRepository = new Mock <ITodosRepository>(); mockedMapper.Setup(m => m.Map <CreatedTodoDTO, Todo>(expectedCreatedTodoDTO)).Returns(todo); mockedMapper.Setup(m => m.Map <CreatedTodoDTO, TodoDTO>(expectedCreatedTodoDTO)).Returns(expectedTodoDTO); mockedRepository.Setup(r => r.CreateTodoAsync(todo)).ReturnsAsync(expectedPrimaryKeyId); var service = new TodosService(mockedMapper.Object, mockedRepository.Object); // Action var actualTodoDTO = await service.CreateTodoAsync(expectedCreatedTodoDTO); // Assert Assert.NotNull(actualTodoDTO); Assert.Equal(expectedPrimaryKeyId, actualTodoDTO.Id); Assert.Equal(expectedTodoDTO.Name, actualTodoDTO.Name); Assert.Equal(expectedTodoDTO.IsComplete, actualTodoDTO.IsComplete); mockedMapper.Verify(m => m.Map <CreatedTodoDTO, Todo>(expectedCreatedTodoDTO), Times.Once()); mockedMapper.Verify(m => m.Map <CreatedTodoDTO, TodoDTO>(expectedCreatedTodoDTO), Times.Once()); mockedRepository.Verify(r => r.CreateTodoAsync(todo), Times.Once()); }
public async Task <bool> UpdateTodo(TodoDTO todo, string id) { _logger.LogInformation("Call to UpdateTodo function made"); using (var session = await _client.StartSessionAsync()) { try { session.StartTransaction(); var model = _mapper.Map <TodoModel>(todo); model.Id = id; var replacedItem = await this.Todos.ReplaceOneAsync(session, x => x.Id == id, model); await session.CommitTransactionAsync(); _logger.LogInformation("Call to UpdateTodo function completed."); return(replacedItem != null); } catch (Exception ex) { _logger.LogInformation("Call to UpdateTodo function was terminate."); await session.AbortTransactionAsync(); throw ex; } } }
public async Task <IActionResult> UpdateTodo(int id, [FromBody] TodoDTO updatedTodo) { if (id != updatedTodo.Id) { return(BadRequest()); } _context.Entry(updatedTodo).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TodoItemExists(id)) { return(NotFound()); } else { throw; } } return(Ok()); }
public async Task CreateTodo_ValidData_ReturnsCreatedAtActionResult() { // Arrange var createdTodoDTO = new CreatedTodoDTO(); var expectedTodoDTO = new TodoDTO() { Id = 1, Name = "Some Todo", IsComplete = true }; var mockService = new Mock <ITodosService>(); mockService.Setup(ts => ts.CreateTodoAsync(createdTodoDTO)).ReturnsAsync(expectedTodoDTO); var controller = new TodosController(mockService.Object); // Action var result = await controller.CreateTodo(createdTodoDTO); // Assert Assert.NotNull(result); Assert.IsType <CreatedAtActionResult>(result.Result); Assert.IsType <TodoDTO>(((CreatedAtActionResult)result.Result).Value); var returnedResultTodo = (TodoDTO)((CreatedAtActionResult)result.Result).Value; Assert.Equal(expectedTodoDTO.Id, returnedResultTodo.Id); Assert.Equal(expectedTodoDTO.Name, returnedResultTodo.Name); Assert.Equal(expectedTodoDTO.IsComplete, returnedResultTodo.IsComplete); }
public async Task <IActionResult> Put(int todoId, TodoDTO todoDTO) { try { var todo = await _repo.GetTodosAsyncById(todoId, false); if (todo == null) { return(NotFound()); } _mapper.Map(todoDTO, todo); _repo.Update(todo); if (await _repo.SaveChangesAsync()) { return(Created($"/api/todo/{todoDTO.Id}", _mapper.Map <TodoDTO>(todo))); } } catch (System.Exception ex) { return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Bd error {ex.Message}")); } return(BadRequest()); }
public void revertNUpdateProductionPlan(TodoDTO item) { MySqlTransaction transaction = conn.BeginTransaction(); try { // delete string insertsql = "DELETE FROM TODO WHERE TodoCode = @TodoCode; "; MySqlCommand insertcomm = new MySqlCommand(insertsql, conn); insertcomm.Transaction = transaction; FillParameters(insertcomm, item); insertcomm.ExecuteNonQuery(); // //update string updatesql = "UPDATE PRODUCTIONPLAN SET PlanedAmount = PlanedAmount - @PlanedAmount WHERE ProductionPlanCode = @ProductionPlanCode; "; MySqlCommand updatecomm = new MySqlCommand(updatesql, conn); updatecomm.Transaction = transaction; updatecomm.Parameters.AddWithValue("@ProductionPlanCode", item.ProductionPlanCode); updatecomm.Parameters.AddWithValue("@PlanedAmount", item.Amount); updatecomm.ExecuteNonQuery(); // transaction.Commit(); } catch (Exception) { transaction.Rollback(); } }
public bool ValidateTodo(TodoDTO todo, string method) { switch (method) { case "POST": if (!ValidateTodoText(todo.todo_text)) { return(false); } break; case "PUT": if (!ValidateTodoId(todo.id)) { return(false); } if (!ValidateTodoProperties(todo.todo_text, todo.completed)) { return(false); } break; default: if (!ValidateTodoId(todo.id)) { return(false); } break; } return(true); }
public List <TodoDTO> SelectAll() { List <TodoDTO> list = new List <TodoDTO>(); string sql = "SELECT TodoCode, MachineID, ProductionID, EmployeeID, ProductionPlanCode, Amount, Complete, CompleteDate FROM TODO; "; MySqlCommand comm = new MySqlCommand(sql, conn); MySqlDataReader reader = comm.ExecuteReader(); TodoDTO dto; while (reader.Read()) { dto = new TodoDTO() { TodoCode = Convert.ToInt32(reader["TodoCode"]), MachineID = reader["MachineID"].ToString(), ProductionID = reader["ProductionID"].ToString(), EmployeeID = reader["EmployeeID"].ToString(), ProductionPlanCode = Convert.ToInt32(reader["ProductionPlanCode"]), Amount = Convert.ToInt32(reader["Amount"]), Complete = Convert.ToChar(reader["Complete"]), CompleteDate = Convert.ToDateTime(reader["CompleteDate"]) }; list.Add(dto); } return(list); }
//public void Insert(TodoDTO item) { //} public void InsertNUpdateProductionPlan(TodoDTO item, int productionPlanCode, int planedAmount) { MySqlTransaction transaction = conn.BeginTransaction(); try { // insert string insertsql = "INSERT INTO TODO(MachineID, ProductionID, EmployeeID, ProductionPlanCode, Amount) VALUES(@MachineID, @ProductionID, @EmployeeID, @ProductionPlanCode, @Amount);"; MySqlCommand insertcomm = new MySqlCommand(insertsql, conn); insertcomm.Transaction = transaction; FillParameters(insertcomm, item); insertcomm.ExecuteNonQuery(); // //update string updatesql = "UPDATE PRODUCTIONPLAN SET PlanedAmount = PlanedAmount + @PlanedAmount WHERE ProductionPlanCode = @ProductionPlanCode; "; MySqlCommand updatecomm = new MySqlCommand(updatesql, conn); updatecomm.Transaction = transaction; updatecomm.Parameters.AddWithValue("@ProductionPlanCode", productionPlanCode); updatecomm.Parameters.AddWithValue("@PlanedAmount", planedAmount); updatecomm.ExecuteNonQuery(); // transaction.Commit(); } catch (Exception) { transaction.Rollback(); } }
public Results.GenericResult Put(int id, [FromBody] TodoDTO model) { var result = new Results.GenericResult(); var validatorResult = validator.Validate(model); if (validatorResult.IsValid) { try { result.Success = appService.Update(model) != null; if (!result.Success) { throw new Exception($"Todo {id} can't be updated"); } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; result.Errors = new string[] { ex.Message }; } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; result.Errors = validatorResult.GetErrors(); } return(result); }
public void CreateTodo_ShouldBeBadRequest() { // Arrange var options = GetTestDbOptions(); using (var context = new ApplicationContext(options)) { var todoService = new TodoService(context, GetMockMapper()); var todoDTO = new TodoDTO() { Name = "test1", Description = "use mock", AssigneeId = 1, Done = false, UserId = 1 }; var expected = new BadRequestResult(); // Act Task <IActionResult> actual = todoService.CreateTodo(todoDTO); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.GetType(), actual.Result.GetType()); } }
public void TodoControllerTest_AddTodo() { // Arrange var mockTodoService = new Mock <ITodoService>(); TodoDTO todoDTO = new TodoDTO { Name = "test", AssigneeId = 1, Description = "test add todo endpoint", Done = false, UserId = 1 }; mockTodoService.Setup(x => x.CreateTodo(todoDTO)) .ReturnsAsync(new OkResult()); TodoController todoController = new TodoController(mockTodoService.Object); // Act Task <IActionResult> addTodoResult = todoController.Post(todoDTO); // Assert var expected = new OkResult(); Assert.IsNotNull(addTodoResult); Assert.AreEqual(expected.GetType(), addTodoResult.Result.GetType()); }
public Results.GenericResult <TodoDTO> Post([FromBody] TodoDTO model) { var result = new Results.GenericResult <TodoDTO>(); var validatorResult = validator.Validate(model); if (validatorResult.IsValid) { try { result.Result = appService.Create(model); result.Success = true; Response.StatusCode = (int)HttpStatusCode.Created; } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; result.Errors = new string[] { ex.Message }; } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; result.Errors = validatorResult.GetErrors(); } return(result); }
public IHttpActionResult DeleteTodo(int id) { string method = "DELETE"; TodoDTO todoDto = new TodoDTO(); todoDto.id = id; if (!_todoBLL.ValidateTodo(todoDto, method)) { return(BadRequest()); } try { using (TodoAppEntities entities = new TodoAppEntities()) { var entity = entities.Todos.FirstOrDefault(todo => todo.id == id); if (entity == null) { return(Content(HttpStatusCode.NotFound, "Todo not found")); } entities.Todos.Remove(entity); entities.SaveChanges(); return(Ok(entity)); } } catch (Exception ex) { return(Content(HttpStatusCode.BadRequest, ex)); } }
public List <TodoDTO> GetTodos(string user) { try { var userfound = db.Users.Where(x => x.UserName == user).FirstOrDefault(); if (userfound != null) { var todos = db.Todos.Where(x => x.User.UserName == user); List <TodoDTO> todosDTO = new List <TodoDTO>(); foreach (var todo in todos) { TodoDTO todoDTO = new TodoDTO() { Message = todo.Message, Id = todo.Id, DateGenerated = todo.DateGenerated, DateUpdated = todo.DateUpdated, FinishDate = todo.FinishDate, Status = todo.Status, UserId = todo.UserId }; todosDTO.Add(todoDTO); } return(todosDTO); } else { return(null); } } catch { return(null); } }
public IHttpActionResult AddTodo([FromBody] Todo todo) { string method = "POST"; TodoDTO todoDto = new TodoDTO(); todoDto.todo_text = todo.todo_text; if (!_todoBLL.ValidateTodo(todoDto, method)) { return(BadRequest()); } try { using (TodoAppEntities entities = new TodoAppEntities()) { entities.Todos.Add(todo); entities.SaveChanges(); return(Ok(todo)); } } catch (Exception ex) { return(Content(HttpStatusCode.BadRequest, ex)); } }
// GET: Todos/Details/5 public async Task <IActionResult> Details(int?id) { if (id == null) { return(NotFound()); } var todo = await _context.Todo .SingleOrDefaultAsync(m => m.Id == id); TodoDTO _tdDto = new TodoDTO(); MyTodo _td = new MyTodo(); DatabaseManager.TodoId = (int)id; _td.Id = DatabaseManager.TodoId; _td.Title = todo.Title; if (todo == null) { return(NotFound()); } _tdDto.AllItems = _context.Item.ToList(); _tdDto.MyTodos = _td; return(View(_tdDto)); }
public TodoDTO GetById(int id) { var parameters = new List <SqlParameter>(); parameters.Add(sqlHelper.CreateParameter("@Id", id, DbType.Int32)); var dataReader = sqlHelper.GetDataReader("sp_GetTodoById", CommandType.StoredProcedure, parameters.ToArray(), out connection); try { var todo = new TodoDTO(); while (dataReader.Read()) { todo.Title = Convert.ToString(dataReader["Title"]); todo.Complete = Convert.ToBoolean(dataReader["Complete"]); todo.Id = Convert.ToInt32(dataReader["Id"]); } return(todo); } catch (Exception ex) { throw ex; } finally { dataReader.Close(); CloseConnection(); } }
private void BtnRemoveTodo_Click(object sender, EventArgs e) { // 작업 취소 버튼 try { TodoDTO dto = new TodoDTO() { }; // 취소 시도 TodoService service = new TodoService(); service.revertNUpdateProductionPlan(new TodoDTO() { TodoCode = Convert.ToInt32(dgvTodo.SelectedRows[0].Cells["TodoCode"].Value), ProductionID = dgvTodo.SelectedRows[0].Cells["ProductionID"].Value.ToString(), MachineID = dgvTodo.SelectedRows[0].Cells["MachineID"].Value.ToString(), EmployeeID = dgvTodo.SelectedRows[0].Cells["EmployeeID"].Value.ToString(), ProductionPlanCode = Convert.ToInt32(dgvTodo.SelectedRows[0].Cells["ProductionPlanCode"].Value), Amount = Convert.ToInt32(dgvTodo.SelectedRows[0].Cells["Amount"].Value) }); service.Dispose(); } catch (Exception ee) { MessageBox.Show(ee.Message); } // 재로드 LoadDgvs(); }
public async Task <TodoDTO> CreateTodo(TodoDTO todo) { var mappedTodo = _mapper.Map <Todo>(todo); var createdTodo = await _todoRepository.CreateTodo(mappedTodo); return(_mapper.Map <TodoDTO>(createdTodo)); }
public Todo UpdateTodo(TodoDTO todo) { var todoEntityToUpdate = _context.Todos.FirstOrDefault(t => t.Id == todo.Id); todoEntityToUpdate.Complete = todo.Complete; todoEntityToUpdate.Title = todo.Title; return(todoEntityToUpdate); }
public void FillParameters(MySqlCommand comm, TodoDTO item) { comm.Parameters.AddWithValue("@Todocode", item.TodoCode); comm.Parameters.AddWithValue("@MachineID", item.MachineID); comm.Parameters.AddWithValue("@ProductionID", item.ProductionID); comm.Parameters.AddWithValue("@EmployeeID", item.EmployeeID); comm.Parameters.AddWithValue("@productionPlanCode", item.ProductionPlanCode); comm.Parameters.AddWithValue("@Amount", item.Amount); }
public IHttpActionResult DeleteTodo([FromBody] TodoDTO todo) { _todoRepository.DeleteTodo(todo.Id); if (!_todoRepository.Save()) { return(BadRequest("A problem happened while handling your request.")); } return(Ok()); }
public async Task <IActionResult> UpdateTodo(string id, [FromBody] TodoDTO updatedTodo) { var isUpdated = await todosService.UpdateTodo(id, updatedTodo); if (isUpdated == false) { return(BadRequest()); } return(Ok()); }