Пример #1
0
        public async void CanUpdateAList()
        {
            DbContextOptions <TodoDbContext> options =
                new DbContextOptionsBuilder <TodoDbContext>()
                .UseInMemoryDatabase("GetTodoListName")
                .Options;

            using (TodoDbContext context = new TodoDbContext(options))
            {
                TodoList list = new TodoList();
                list.ListTitle = "test";

                context.TodoLists.Add(list);
                context.SaveChanges();

                list.ListTitle = "update";

                context.TodoLists.Update(list);
                context.SaveChanges();

                var listContents = await context.TodoLists.FirstOrDefaultAsync(x => x.ListTitle == list.ListTitle);

                Assert.Equal("update", listContents.ListTitle);
            }
        }
Пример #2
0
        //public List<Todo> GetTodos(string filter)
        //{
        //    var filterOn = filter.Split(',');
        //    var todoList = _context.Todos.Select(s => new { s.Id, s.Title }).ToList();
        //    return todoList;
        //}

        public int StoreTodo(TodoMapper mapper)
        {
            var newTodo = new Todo();

            if (mapper.Id > 0)
            {
                newTodo = _context.Todos.Find(mapper.Id);
            }

            newTodo.Title       = mapper.Title;
            newTodo.Description = mapper.Description;
            newTodo.Status      = (TaskStatus)mapper.Status;
            newTodo.Created     = mapper.Created;
            newTodo.Due         = mapper.Due;
            newTodo.Completed   = mapper.Completed;
            newTodo.OwnerId     = 1;

            if (mapper.Id == 0)
            {
                _context.Entry(newTodo).State = Microsoft.EntityFrameworkCore.EntityState.Added;
            }
            else
            {
                _context.Entry(newTodo).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            }

            return(_context.SaveChanges());
        }
Пример #3
0
        // PUT api/Todo/5
        public HttpResponseMessage PutTodos(int id, Todos todos)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != todos.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            db.Entry(todos).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #4
0
        public IHttpActionResult PutTaskList(int id, TaskList taskList)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != taskList.Id)
            {
                return BadRequest();
            }

            db.Entry(taskList).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskListExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Пример #5
0
        public async void CanUpdateTodo()
        {
            DbContextOptions <TodoDbContext> options =
                new DbContextOptionsBuilder <TodoDbContext>()
                .UseInMemoryDatabase("GetTodoName")
                .Options;

            using (TodoDbContext context = new TodoDbContext(options))
            {
                Todo task = new Todo();
                task.Title = "test";

                context.Todos.Add(task);
                context.SaveChanges();

                task.Title = "update";

                context.Todos.Update(task);
                context.SaveChanges();

                var taskTitle = await context.Todos.FirstOrDefaultAsync(x => x.Title == task.Title);

                Assert.Equal("update", taskTitle.Title);
            }
        }
Пример #6
0
        public async void CanDeleteATodo()
        {
            //Arrange
            DbContextOptions <TodoDbContext> options =
                new DbContextOptionsBuilder <TodoDbContext>()
                .UseInMemoryDatabase("GetTodoName")
                .Options;

            using (TodoDbContext context = new TodoDbContext(options))
            {
                Todo task = new Todo();
                task.Title = "testTodo";

                context.Todos.Add(task);
                context.SaveChanges();

                //Act
                context.Todos.Remove(task);
                context.SaveChanges();

                var taskTitle = await context.Todos.ToListAsync();

                //Assert
                Assert.DoesNotContain(task, taskTitle);
            }
        }
Пример #7
0
        public async void CanDeleteAList()
        {
            //Arrange
            DbContextOptions <TodoDbContext> options =
                new DbContextOptionsBuilder <TodoDbContext>()
                .UseInMemoryDatabase("GetTodoListName")
                .Options;

            using (TodoDbContext context = new TodoDbContext(options))
            {
                TodoList list = new TodoList();
                list.Title = "testList";

                context.TodoLists.Add(list);
                context.SaveChanges();

                //Act
                context.TodoLists.Remove(list);
                context.SaveChanges();

                var listContents = await context.TodoLists.ToListAsync();

                //Assert
                Assert.DoesNotContain(list, listContents);
            }
        }
        public IHttpActionResult PutTodo(int id, Todo todo)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != todo.Id)
            {
                return(BadRequest());
            }

            db.Entry(todo).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TodoExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #9
0
        /// <summary>
        /// Initiate a new todo list for new user
        /// </summary>
        /// <param name="userName"></param>
        internal static void InitiateDatabaseForNewUser(string userName)
        {
            using (TodoDbContext db = new TodoDbContext())
            {
                TodoList todoList = new TodoList();
                todoList.UserId = userName;
                todoList.Title  = "My Todo List #1";
                todoList.Todos  = new List <TodoItem>();
                db.TodoLists.Add(todoList);
                db.SaveChanges();

                todoList.Todos.Add(new TodoItem()
                {
                    Title      = "Todo item #1",
                    TodoListId = todoList.TodoListId,
                    IsDone     = false
                });
                todoList.Todos.Add(new TodoItem()
                {
                    Title      = "Todo item #2",
                    TodoListId = todoList.TodoListId,
                    IsDone     = false
                });
                db.SaveChanges();
            }
        }
Пример #10
0
        public IHttpActionResult PutTodoList(int id, TodoListViewModel todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return(Message(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)));
            }

            if (id != todoListDto.TodoListId)
            {
                return(StatusCode(HttpStatusCode.BadRequest));
            }

            TodoList todoList = todoListDto.ToEntity();

            if (!String.Equals(db.Entry(todoList).Entity.UserId, User.Identity.GetUserId(), StringComparison.OrdinalIgnoreCase))
            {
                // Trying to modify a record that does not belong to the user
                return(StatusCode(HttpStatusCode.Unauthorized));
            }

            db.Entry(todoList).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return(StatusCode(HttpStatusCode.InternalServerError));
            }

            return(StatusCode(HttpStatusCode.OK));
        }
Пример #11
0
 public void Add(TodoItem todoItem)
 {
     if(_context.TodoItems.Find(todoItem.Id) != null) 
         throw new DuplicateTodoItemException
             ($"Duplicate id: {todoItem.Id}");
     _context.TodoItems.Add(todoItem);
     _context.SaveChanges();
 }
        public ActionResult <TodoItem> AddTodoItem(TodoItem item)
        {
            Task.Delay(Config.ActionDelay).Wait();

            _dbContext.TodoItems.Add(item);
            _dbContext.SaveChanges();

            return(CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item));
        }
Пример #13
0
 public void Add(TodoItem todoItem)
 {
     if (_context.TodoItems.FirstOrDefault(g => g.Id == todoItem.Id) != null)
     {
         throw new DuplicateTodoItemException($"duplicate id: {todoItem.Id}");
     }
     _context.TodoItems.Add(todoItem);
     _context.SaveChanges();
 }
        public IActionResult Create(Todo todo)
        {
            var todoId = _dbContext.Todos.Select(x => x.Id).Max() + 1;

            todo.Id = todoId;
            _dbContext.Todos.Add(todo);
            _dbContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Пример #15
0
 public ActionResult <Todo> Post([FromBody] Todo todo)
 {
     if (todo == null)
     {
         return(StatusCode((int)HttpStatusCode.NotAcceptable));
     }
     todo.Timestamp = DateTime.Now;
     dbContext.Todos.Add(todo);
     dbContext.SaveChanges();
     return(todo);
 }
Пример #16
0
        public async void Add(TodoItem todoItem)
        {
            TodoItem ret = await _context.TodoItems.FirstOrDefaultAsync(i => i.Id.Equals(todoItem.Id));

            if (ret != null)
            {
                throw new DuplicateTodoItemException("duplicate id: { " + todoItem.Id + "}");
            }
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();
        }
Пример #17
0
        public IActionResult Create([FromBody] TodoTask task)
        {
            if (task == null)
            {
                return(BadRequest());
            }

            _context.TodoTasks.Add(task);
            _context.SaveChanges();

            return(CreatedAtRoute("get", new { id = task.TodoTaskId }, task));
        }
        public IActionResult Post([FromBody] TodoDTO model) => RunSafely(() =>
        {
            var entity = new Todo.API.Data.Todo
            {
                Name    = model.Name,
                Content = model.Name
            };
            _todoDbContext.Todos.Add(entity);
            _todoDbContext.SaveChanges();

            return(Ok());
        });
Пример #19
0
        public IActionResult Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            _context.TodoItems.Add(item);
            _context.SaveChanges();

            return(CreatedAtRoute("GetTodo", new { id = item.Id }, item));
        }
Пример #20
0
        public IActionResult CreateList(TodoList list)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            _db.TodoLists.Add(list);
            _db.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }
Пример #21
0
        public void CreateTodo(string txt)
        {
            var todo = new Todo()
            {
                Txt = txt
            };

            ctx.Todos.Add(todo);
            ctx.SaveChanges();

            Clients.All.createdTodo(todo);
        }
Пример #22
0
        public ActionResult Create(string txt)
        {
            var todo = new Todo()
            {
                Txt = txt
            };

            db.Todos.Add(todo);
            db.SaveChanges();

            return(Content(JsonConvert.SerializeObject(todo), "application/json"));
        }
Пример #23
0
 public IHttpActionResult PostCategories(Categorie categorie)
 {
     if (ModelState.IsValid)  // si l'état du modele est ok, càd que le tous les champs sont non nulls
     {
         db.Categories.Add(categorie);
         db.SaveChanges();
         return(Ok(categorie));
     }
     else
     {
         return(BadRequest(ModelState)); // renvoie une errueur 400
     }
 }
 public IHttpActionResult PostCategories(Categorie categorie)
 {
     if (ModelState.IsValid)
     {
         db.Categories.Add(categorie);
         db.SaveChanges();
         return(Ok(categorie));
     }
     else
     {
         return(BadRequest(ModelState));
     }
 }
Пример #25
0
        public void CreateTodo(Todos todo)
        {
            TodoEntity todoEntity = new TodoEntity
            {
                DateAdded      = todo.DateAdded,
                DateToCommence = todo.DateToCommence,
                Description    = todo.Description,
                Title          = todo.Title,
                UserId         = todo.UserId
            };

            todoDbContext.TodoEntities.Add(todoEntity);
            todoDbContext.SaveChanges();
        }
Пример #26
0
        public void Add(TodoItem todoItem)
        {
            if (todoItem == null)
            {
                throw new ArgumentNullException();
            }
            if (_context.TodoItems.Any(t => t.Id.Equals(todoItem.Id)))
            {
                throw new DuplicateTodoItemException(todoItem.Id);
            }

            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();
        }
        private void CreateEditions()
        {
            var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);

            if (defaultEdition == null)
            {
                defaultEdition = new Edition {
                    Name = EditionManager.DefaultEditionName, DisplayName = EditionManager.DefaultEditionName
                };
                _context.Editions.Add(defaultEdition);
                _context.SaveChanges();

                /* Add desired features to the standard edition, if wanted... */
            }
        }
Пример #28
0
        public IHttpActionResult PostCategories(Categorie categorie)
        {
            // afin de verifier les models de la table crée il faut la ligne suivante
            if (ModelState.IsValid)
            {
                db.Categories.Add(categorie);
                db.SaveChanges();

                return(Ok(categorie)); // return "..." permet de retourner le code d'acces du server à la connexion de la base de donnée Ok = Status 200)
            }
            else
            {
                return(BadRequest(ModelState)); //Permet de sortir l'ereur 400 dans la console web ainsi avec un resumé de l'erreure
            }
        }
        public IActionResult OnPost()
        {
            _dbContext.Todos.Add(Todo);
            _dbContext.SaveChanges();

            return(RedirectToPage("./Index"));
        }
Пример #30
0
        public async Task Create_ReturnsNewlyCreatedTodoItem()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <TodoDbContext>()
                          .UseInMemoryDatabase(databaseName: "Create_ReturnsNewlyCreatedTodoItem")
                          .Options;

            var context = new TodoDbContext(options);

            context.Items.AddRange(
                Enumerable.Range(1, 10).Select(t => new Item {
                Description = "Item " + t
            })
                );

            context.SaveChanges();

            var controller = new ItemsController(context);

            // Act
            var result = await controller.Create(new Item { Description = "This is a new task" });

            // Assert
            Assert.IsType <CreatedAtRouteResult>(result);
            Assert.Equal(11, context.Items.Count());
        }