Ejemplo n.º 1
0
        // GET api/TodoList
        public IEnumerable <TodoListDto> GetTodoLists()
        {
            //return db.TodoLists.Include("Todos")
            //    .Where(u => u.UserId == User.Identity.Name)
            //    .OrderByDescending(u => u.TodoListId)
            //    .AsEnumerable()
            //    .Select(todoList => new TodoListDto(todoList));
            List <TodoItemDto> todoItemDtos = new List <TodoItemDto>();

            for (int i = 0; i < 3; i++)
            {
                TodoItemDto todoItemDto = new TodoItemDto()
                {
                    IsDone     = i % 2 == 0,
                    Title      = string.Format("Title {0}", i),
                    TodoItemId = i,
                    TodoListId = 1
                };
                todoItemDtos.Add(todoItemDto);
            }

            TodoListDto todoListDto = new TodoListDto
            {
                TodoListId = 1,
                UserId     = "hungndv",
                Title      = "Title",
                Todos      = todoItemDtos
            };
            List <TodoListDto> todoListDtos = new List <TodoListDto>();

            todoListDtos.Add(todoListDto);
            return(todoListDtos);
        }
Ejemplo n.º 2
0
        public TodoListAggregate GetById(object listId)
        {
            const string sql = "SELECT list.[Id] 'Id', list.[ListId] 'ListId', list.[Name], item.[Id] 'Id', item.[ItemId] 'ItemId', item.[Text], item.[IsCompleted], item.[TodoList_Id] " +
                               "FROM TodoList list " +
                               "LEFT JOIN [TodoItem] item ON item.[TodoList_Id] = list.[Id] " +
                               "WHERE list.[ListId] = @listId";

            TodoListDto todoList = null;
            var         items    = new List <TodoListItemDto>();

            using (var c = _sqlConnectionProvider.GetConnection())
            {
                c.Query <TodoListDto, TodoListItemDto, TodoListDto>(sql, (list, item) =>
                {
                    if (todoList == null)
                    {
                        todoList = list;
                    }
                    if (item != null) //if there is element
                    {
                        items.Add(item);
                    }

                    return(todoList);
                }, new { listId = listId }, splitOn: "Id");
            }
            if (todoList == null)
            {
                return(null);
            }

            return(TodoListAggregate.Map.From(todoList, items));
        }
Ejemplo n.º 3
0
        public HttpResponseMessage DeleteTodoList(int id)
        {
            TodoList todoList = db.TodoLists.Find(id);
            if (todoList == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Trying to delete a record that does not belong to the user
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }

            TodoListDto todoListDto = new TodoListDto(todoList);
            db.TodoLists.Remove(todoList);

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

            return Request.CreateResponse(HttpStatusCode.OK, todoListDto);
        }
Ejemplo n.º 4
0
        public HttpResponseMessage DeleteTodoList(int id)
        {
            TodoList todoList = db.TodoLists.Find(id);

            if (todoList == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Intentando eliminar un registro que no pertenece al usuario
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            TodoListDto todoListDto = new TodoListDto(todoList);

            db.TodoLists.Remove(todoList);

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

            return(Request.CreateResponse(HttpStatusCode.OK, todoListDto));
        }
Ejemplo n.º 5
0
        public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

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

            TodoList todoList = todoListDto.ToEntity();

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Intentando modificar un registro que no pertenece al usuario
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

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

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 6
0
 public TodoList(TodoListDto listDto)
 {
     Name    = listDto.Name;
     Tasks   = listDto.Tasks.ConvertAll(x => new Task(x)).ToList();
     OwnerId = listDto.OwnerId;
     Status  = listDto.Status;
 }
Ejemplo n.º 7
0
        public HttpResponseMessage DeleteTodoList(int id)
        {
            TodoList todoList = db.TodoLists.Find(id);

            if (todoList == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Trying to delete a record that does not belong to the user
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            TodoListDto todoListDto = new TodoListDto(todoList);

            db.TodoLists.Remove(todoList);

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

            return(Request.CreateResponse(HttpStatusCode.OK, todoListDto));
        }
        public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

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

            TodoList todoList = todoListDto.ToEntity();
            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }

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

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

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Ejemplo n.º 9
0
        public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

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

            TodoList todoList = todoListDto.ToEntity();

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

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

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Put(string id, [FromBody] TodoListDto input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }
            if (id != input.Id.ToString())
            {
                return(BadRequest());
            }
            if (input.TodoId.HasValue)
            {
                var result = await _todoListAppService.AddTodoItemToTodoListAsync(id, input.TodoId.Value);

                if (result == null)
                {
                    return(NotFound());
                }
            }
            else
            {
                var result = await _todoListAppService.UpdateTodoListItemAsync(id, input);

                if (result == null)
                {
                    return(NotFound());
                }
            }
            return(NoContent());
        }
Ejemplo n.º 11
0
 // POST api/lists
 public IHttpActionResult Post([FromBody] TodoListDto value)
 {
     if (!ValidatePost(value))
     {
         return(BadRequest("Ensure list has name field..."));
     }
     return(Ok(ToDto(_todoRepository.AddList(value.name))));
 }
Ejemplo n.º 12
0
        public bool CreateTodoList(TodoListDto requestModel)
        {
            TodoList newModel = _todoListModelFactory.Map(requestModel);

            newModel.SetOwner(_context.Users.SingleOrDefault(x => x.Id == requestModel.OwnerId));
            _context.TodoLists.Add(newModel);
            return(_context.SaveChanges() > 0);
        }
Ejemplo n.º 13
0
 public static TodoList ToDatabaseObject(this TodoListDto dto)
 {
     return(new TodoList()
     {
         Items = dto.Items.Select(x => x.ToDatabaseObject()).ToList(),
         Name = dto.Name,
         Id = dto.Id
     });
 }
Ejemplo n.º 14
0
        private async Task <TodoListDto> mapTodoDto(TodoListModel item)
        {
            TodoListDto mappedDto = new TodoListDto();

            mappedDto.Id          = item.Id;
            mappedDto.Name        = item.Name;
            mappedDto.Description = item.Description;
            mappedDto.Tasks       = await _repository.getTasksByTodoIdAsync(item.Id);

            return(mappedDto);
        }
Ejemplo n.º 15
0
        // PUT api/lists/5
        public IHttpActionResult Put(int id, [FromBody] TodoListDto value)
        {
            var list = new TodoList(id, value.name);

            list = _todoRepository.UpdateList(list);
            if (list == null)
            {
                return(NotFound());
            }
            return(Ok(ToDto(list)));
        }
Ejemplo n.º 16
0
        public async Task <ActionResult <TodoListDto> > Post([FromBody] TodoListDto data)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }
            var insertedId = await _todoListAppService.AddTodoListAsync(data);

            data.Id = insertedId;
            return(CreatedAtAction(nameof(Get), new { id = insertedId }, data));
        }
Ejemplo n.º 17
0
        public void Save(TodoListAggregate listEntity)
        {
            var listDto        = new TodoListDto();
            var resultItemList = new List <TodoListItemDto>();

            DtoMapper.Map(listEntity, listDto);
            using (var c = _sqlConnectionProvider.GetConnection())
            {
                using (var tran = c.BeginTransaction())
                {
                    try
                    {
                        if (listEntity.Key == 0)
                        {
                            const string insertTodoListSql = "INSERT INTO [TodoList]([ListId],[Name]) OUTPUT INSERTED.[Id] VALUES(@listId, @name)";
                            listDto.Id = c.QuerySingle <int>(insertTodoListSql, new { listId = listDto.ListId, name = listDto.Name }, tran);
                        }
                        else
                        {
                            //const string insertTodoListSql = "UPDATE [TodoList]([Name]) VALUES(@Name)";
                            c.Update(listDto, tran);
                        }

                        //remove deleted items
                        const string deleteRemovedSql = "DELETE FROM [TodoItem] WHERE [TodoList_Id] = @listId AND Id NOT IN @ids";
                        c.Execute(deleteRemovedSql, new { listId = listDto.Id, ids = listEntity.Items.Select(e => e.Key) }, tran);

                        foreach (var itemEntity in listEntity.Items)
                        {
                            var dto = new TodoListItemDto();
                            DtoMapper.Map(listDto.Id, itemEntity, dto);

                            if (itemEntity.Key == 0)
                            {
                                dto.Id = (int)c.Insert(dto, tran);
                            }
                            else if (itemEntity.Key > 0)
                            {
                                c.Update(dto, tran);
                            }

                            resultItemList.Add(dto);
                        }

                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 18
0
            public static TodoListAggregate From(TodoListDto dto, IEnumerable <TodoListItemDto> dtos)
            {
                var model = new TodoListAggregate()
                {
                    Key    = dto.Id,
                    ListId = dto.ListId,
                    Name   = dto.Name,
                };

                model._items.AddRange(dtos.Select(TodoItem.Map.From));
                return(model);
            }
Ejemplo n.º 19
0
 private static bool ValidatePost(TodoListDto list)
 {
     if (list == null)
     {
         return(false);
     }
     if (string.IsNullOrWhiteSpace(list.name))
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 20
0
        public async Task <IActionResult> AddTodoList([FromBody] TodoListDto todoListDto)
        {
            var todoList = _mapper.Map <TodoList>(todoListDto);

            todoList.UserId = _userId;

            await _db.TodoLists.AddAsync(todoList);

            await _db.SaveChangesAsync();

            return(Ok());
        }
Ejemplo n.º 21
0
        public async Task <Guid> AddTodoListAsync(TodoListDto input)
        {
            TodoList entity = new TodoList
            {
                Name   = input.Name,
                UserId = GetCurrentUserId()
            };
            await _context.TodoLists.AddAsync(entity).ConfigureAwait(false);

            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(entity.Id);
        }
Ejemplo n.º 22
0
        public async Task <TodoListDto> UpdateTodoListItemAsync(string id, TodoListDto input)
        {
            var existingEntity = await _context.TodoLists.FirstOrDefaultAsync(q => q.Id == new Guid(id)).ConfigureAwait(false);

            existingEntity.Name = input.Name;
            _context.TodoLists.Update(existingEntity);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(new TodoListDto
            {
                Id = existingEntity.Id,
                Name = existingEntity.Name
            });
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> CreateTodoAsync([FromBody] TodoListDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("The given model is incorrectly formatted."));
            }

            var todo = await _todoService.CreateTodoAsync(dto);

            if (todo == null)
            {
                return(BadRequest("Todo could not be created."));
            }

            return(CreatedAtRoute("GetTodoById", new { id = todo.Id }, todo));
        }
        public HttpResponseMessage PostTodoList(TodoListDto todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            todoListDto.UserId = User.Identity.Name;
            TodoList todoList = todoListDto.ToEntity();
            db.TodoLists.Add(todoList);
            db.SaveChanges();
            todoListDto.TodoListId = todoList.TodoListId;

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, todoListDto);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = todoListDto.TodoListId }));
            return response;
        }
        public async Task <List <TodoListDto> > GetTodoLists(ClaimsPrincipal principal)
        {
            var userIdString = principal?.Claims?.FirstOrDefault(c => c.Type == "user_id")?.Value;
            var todoListDto  = new List <TodoListDto>();

            var userId         = long.Parse(userIdString);
            var todoListEntity = await _unitOfWork.FindAsyncByPredicateWithIncludeProperty <TodoTransactionEntity>(x => x.UserId == userId, e => e.User);

            todoListEntity = todoListEntity.OrderByDescending(x => x.CreatedDate).ToList();
            //automapper can be used
            foreach (var todo in todoListEntity)
            {
                var todoDto = new TodoListDto(todo);
                todoListDto.Add(todoDto);
            }
            return(todoListDto);
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> UpdateTodoAsync(int id, [FromBody] TodoListDto todo)
        {
            var originalTodo = await _todoService.GetById(id);

            if (originalTodo == null)
            {
                return(NotFound());
            }

            if (id != todo.Id)
            {
                return(BadRequest($"The given id does not match the id of the given todo ({id} != {todo.Id})."));
            }

            var updatedTodo = await _todoService.UpdateTodoAsync(todo);

            return(Ok(updatedTodo));
        }
Ejemplo n.º 27
0
        public HttpResponseMessage PostTodoList(TodoListDto todoListDto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            todoListDto.UserId = User.Identity.Name;
            TodoList todoList = todoListDto.ToEntity();

            db.TodoLists.Add(todoList);
            db.SaveChanges();
            todoListDto.TodoListId = todoList.TodoListId;

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, todoListDto);

            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = todoListDto.TodoListId }));
            return(response);
        }
Ejemplo n.º 28
0
        public IActionResult GetTodoList(int id)
        {
            var list = service.GetById(id);
            var dto  = new TodoListDto
            {
                Id        = list.Id,
                Title     = list.Title,
                TodoItems = list.TodoItems.Select(e => new TodoItemDto
                {
                    Id          = e.Id,
                    Title       = e.Title,
                    Description = e.Description,
                    DueDate     = e.DueDate,
                    Done        = e.Done
                }).ToList()
            };

            return(Ok(dto));
        }
Ejemplo n.º 29
0
        public async Task Handle(InvitationSent notification, CancellationToken cancellationToken)
        {
            var list = await _todoListRepository.FindTodoListIdByIdAsync(notification.ListId.GetValueOrDefault());

            var invitee = await _accountRepository.FindAccountByIdAsync(notification.InviteeAccountId);

            var accountsLists = await _accountsListsRepository.FindAccountsListsByAccountIdAndListIdAsync(invitee.Id, list.Id);

            var listModel = new TodoListDto()
            {
                Id           = list.Id,
                Contributors = list.Contributors,
                Role         = accountsLists.Role,
                ListTitle    = list.ListTitle,
                Completed    = list.Completed
            };

            await _hubContext.Clients.User(invitee.Email).SendAsync("InvitationSent", listModel);
        }
Ejemplo n.º 30
0
        public async Task <TodoListDto> DeleteTodoListAsync(string id)
        {
            var existingEntity = await _context.TodoLists.FirstOrDefaultAsync(q => q.Id == new Guid(id)).ConfigureAwait(false);

            TodoListDto dto = existingEntity == null ? null : new TodoListDto
            {
                Id   = existingEntity.Id,
                Name = existingEntity.Name
            };

            if (existingEntity != null)
            {
                var effectedTodoItems = _context.TodoItems.Where(q => q.TodoListId == existingEntity.Id).ToList();
                effectedTodoItems.ForEach(q => q.TodoListId = null);

                _context.TodoLists.Remove(existingEntity);
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            return(dto);
        }
Ejemplo n.º 31
0
        public IActionResult CreateNewList([FromBody] TodoListDto value)
        {
            // Create new list
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                _service.CreateList(value);
            }
            catch
            {
                // TODO return the correct respnce.
                return(null);
            }

            return(CreatedAtAction("Get", new { id = value.Id }, value));
        }
Ejemplo n.º 32
0
        public async Task CreateList(TodoListDto list)
        {
            // todo find out in the controller what we need to pass in and create
            // the following object
            var           tasks   = list.Tasks.Where(x => x.Id != null);
            TodoListModel newList = new TodoListModel
            {
                Id          = list.Id,
                Name        = list.Name,
                Description = list.Description
            };

            foreach (var task in tasks)
            {
                task.ListId = list.Id;
            }
            // create the list first so the foreign key is there.
            await _repository.AddLisAsynct(newList);

            // add the tasks
            await _repository.AddTaskAsync(tasks);
        }
Ejemplo n.º 33
0
 public static void Map(TodoListAggregate entity, TodoListDto dto)
 {
     dto.Id     = entity.Key;
     dto.ListId = entity.ListId;
     dto.Name   = entity.Name;
 }