public ActionResult Create(CreateTodoViewModel model) { if (ModelState.IsValid) { DateTime startDate = GetDateTimeFromString(model.StartDate, model.StartTime); DateTime dueDate = GetDateTimeFromString(model.DueDate, model.DueTime); Todo todo = new Todo { Title = model.Title, Description = model.Description, StartDate = startDate, DueDate = dueDate, AssignedTo = model.AssignedTo, Owner = model.Owner }; todoRepository.Create(todo); TempData["TodoSuccess"] = "Todo item " + todo.Title + " added successfully"; return(RedirectToAction("Index", "Home")); } model.RegisteredUsers = GetRegisteredUsers(); return(View(model)); }
// GET: ToDo public ActionResult Create() { CreateTodoViewModel model = CreateTodoViewModel(); return(View(model)); }
public async Task Create_UserDoesExist_CreatedAtRoute() { // Arrange var user = MockApplicationUsers.Get(8); var token = await GetToken(user); const string createPath = Routes.TodoRoute; _endSystems.SetBearerToken(token); var model = new CreateTodoViewModel { Description = "I am your doctor, when you need, want some coke? Have some weed", Due = new DateTime(2000, 1, 1) }; var body = JsonStringBuilder.CreateTodoJsonBody(model.Description, model.Due.ToString()); var content = new StringContent(body); // Act var createResponse = await _endSystems.Post(createPath, content); var location = createResponse.Headers.Location.ToString(); var getResponse = await _endSystems.Get(location); var dto = JsonStringSerializer.GetTodoDto(getResponse.Body); // Assert Assert.Equal(HttpStatusCode.Created, createResponse.Code); Assert.Equal(HttpStatusCode.OK, getResponse.Code); Assert.Equal(model.Description, dto.Description); Assert.Equal(model.Due, dto.Due); // Tear down _endSystems.Dispose(); }
public async Task <Todo> CreateTodoFromModelAsync(CreateTodoViewModel model, ApplicationUser user) { var todo = new Todo { Title = model.Title.Trim(), Summary = model.Summary.Trim(), Deadline = model.Deadline, Hashtag = ValidateHashtag(model.Hashtag), Priority = model.Priority, User = user }; if (model.AttachedFile != null) { var stream = model.AttachedFile.OpenReadStream(); string fileName = $"{Guid.NewGuid()}{model.AttachedFile.FileName}"; var blobInfo = await blobClient.UploadFileAsync(fileName, stream); todo.FileUrl = blobInfo.Uri.AbsoluteUri; todo.FileName = fileName; } return(todo); }
public async Task <IActionResult> CreateTodo([FromBody] CreateTodoViewModel model) { if (model == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var id = await _todoService.CreateTodoAsync(model, GetUserId()); return(CreatedAtRoute( MethodNames.GetSingleTodoMethodName, new { todoId = id }, null )); } catch (UserNotFoundException) { return(Unauthorized()); } }
/// <summary> /// Map a view model to a corresponding entity. /// </summary> /// <param name="model">A model for creating todos</param> /// <param name="user">The owner of this todo</param> public Todo(CreateTodoViewModel model, ApplicationUser user) { //Due = model.Due.Value; if (model.Due != null) { Due = model.Due.Value; } Description = string.Copy(model.Description); Owner = user; }
public void CreateTodoViewModel_Getter_Matches() { // Arrange // Act var todo = new CreateTodoViewModel { Description = "Apply dry rub", Due = new DateTime(2011, 5, 1, 4, 15, 0) }; Assert.Equal("Apply dry rub", todo.Description); Assert.Equal(new DateTime(2011, 5, 1, 4, 15, 0), todo.Due); }
private CreateTodoViewModel CreateTodoViewModel() { List <SelectListItem> registeredUsers = GetRegisteredUsers(); CreateTodoViewModel model = new CreateTodoViewModel { StartDate = DateTime.Now.Date.ToString("yyyy/MM/dd"), StartTime = DateTime.Now.ToString("hh:mm:ss tt"), RegisteredUsers = registeredUsers, Owner = GetCurrentUser().Id }; return(model); }
public async Task CreateTodoAsync_NonExistingUser_UserNotFoundException() { // Arrange const string userId = "c54a85fa-ca7c-49d7-b830-6b07ea49cfa8"; var model = new CreateTodoViewModel { Description = "Buy a pie from Frank Pepe's", Due = DateTime.Now }; // Act // Assert await Assert.ThrowsAsync <UserNotFoundException>(() => _service.CreateTodoAsync(model, userId)); }
public void CreateTodoViewModel_DescriptionMissing_Error() { // Arrange var model = new CreateTodoViewModel { Due = DateTime.Now }; // Act var validation = ModelValidator.ValidateModel(model); var errorMessage = validation.Select(x => x.ErrorMessage).SingleOrDefault(); // Assert Assert.Single(validation); Assert.Equal(ErrorMessages.TodoDescriptionRequired, errorMessage); }
public ActionResult <GetTodoViewModel> Post(CreateTodoViewModel model) { try { var dto = _todoService.Create(new CreateTodoDTO { Text = model.Text }); var todo = new GetTodoViewModel { Id = dto.Id, Text = dto.Text, Completed = dto.Completed }; return(StatusCode(201, todo)); } catch (Exception e) { return(BadRequest(e)); } }
public void CreateTodoViewModel_DescriptionTooLong_Error() { // Arrange var len = TodoLimits.DescriptionMaxLength + 1; var model = new CreateTodoViewModel { Description = new StringBuilder(len).Insert(0, "A", len).ToString(), Due = DateTime.Now }; // Act var validation = ModelValidator.ValidateModel(model); var errorMessage = validation.Select(x => x.ErrorMessage).SingleOrDefault(); // Assert Assert.Single(validation); Assert.Equal(ErrorMessages.TodoDescriptionMaxLength, errorMessage); }
public async Task <IActionResult> Create(CreateTodoViewModel model) { if (ModelState.IsValid) { // add todo and bing it to signed in user var signedInUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value; var user = await userManager.FindByIdAsync(signedInUserId); var todo = await viewModelService.CreateTodoFromModelAsync(model, user); await todoRepository.AddAsync(todo); await SendUserDateOnTodosUpdateAsync(); return(RedirectToAction("index", "todos")); } return(View()); }
/// <inheritdoc /> /// <exception cref="UserNotFoundException">When todo is not found</exception> public async Task <int> CreateTodoAsync(CreateTodoViewModel todo, string userId) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { throw new UserNotFoundException(); } var newTodo = new Todo(todo, user); await _db.AddAsync(newTodo); await _db.SaveChangesAsync(); // Add to single cache and clear list cache _cache.Set(CacheConstants.GetSingleTodoCacheKey(newTodo.Id, userId), newTodo, CacheConstants.GetDefaultCacheOptions()); _cache.Remove(CacheConstants.GetAllTodosCacheKey(userId)); _cache.Remove(CacheConstants.GetAllTodosForDayCacheKey(userId, newTodo.Due)); return(newTodo.Id); }
public async Task CreateTodoAsync_ExistingUser_IdOfNewlyCreatedTodo() { // Arrange var userId = MockApplicationUsers.Get(4).Id; var model = new CreateTodoViewModel { Description = "Get a cone from Milkcraft", Due = new DateTime(2019, 5, 1, 12, 0, 0) }; var expectedId = MockTodos.FirstId + MockTodos.GetAll().Count(); // Act var id = await _service.CreateTodoAsync(model, userId); var todo = _ctx.Todo.SingleOrDefault(z => z.Id == expectedId && z.Owner.Id == userId); // Assert Assert.Equal(expectedId, id); Assert.NotNull(todo); Assert.Equal("Get a cone from Milkcraft", todo.Description); Assert.Equal(new DateTime(2019, 5, 1, 12, 0, 0), todo.Due); }
public async Task Create_UserDoesNotExistAnymote_Unauthorized() { // Arrange var user = MockApplicationUsers.Get(5); var admin = MockApplicationUsers.Get(0); var userToken = await GetToken(user); var adminToken = await GetToken(admin); var deletePath = $"{Routes.UserRoute}/{user.Id}"; const string createPath = Routes.TodoRoute; _endSystems.SetBearerToken(adminToken); var deleteResponse = await _endSystems.Delete(deletePath); Assert.Equal(HttpStatusCode.NoContent, deleteResponse.Code); _endSystems.RemoveBearerToken(); _endSystems.SetBearerToken(userToken); var model = new CreateTodoViewModel { Description = "They paved paradise and put up a parking lot", Due = new DateTime(2000, 1, 1) }; var body = JsonStringBuilder.CreateTodoJsonBody(model.Description, model.Due.ToString()); var content = new StringContent(body); // Act var response = await _endSystems.Post(createPath, content); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.Code); // Tear down _endSystems.Dispose(); }
public ActionResult Create(CreateTodoViewModel formData) { //Example of a server side validation only //Goes to the database first and //check if the task is duplicated by Title //Some code here that we haven't learned. //var isTaskDuplicated = true; //if (isTaskDuplicated) //{ // ModelState.AddModelError(nameof(CreateTodoViewModel.Title), // "This task already exists"); //} //ModelState.AddModelError("", "Generic erro happened"); if (!ModelState.IsValid) { return(View()); } //creating a todo var newTodo = new Todo(); newTodo.Id = 1; newTodo.Title = formData.Title; newTodo.Description = formData.Description; newTodo.DueDate = formData.DueDate; //saving to the database TodoInMemoryDatabase.Add(newTodo); //Redirect the user to the todo list return(Redirect(nameof(TodoController.Index))); }
public CreateTodoDialog(CreateTodoViewModel vm) { ViewModel = vm; }
public CreateTodoDialog(CreateTodoViewModel vm) { this.InitializeComponent(); DataContext = vm; Closing += CreateCategoryDialog_Closing; }
/// <inheritdoc /> public async Task <int> CreateTodoAsync(CreateTodoViewModel todo, string userId) { await Task.Run(() => { }); return(MCreateTodoAsync(todo, userId)); }