Ejemplo n.º 1
0
        public async Task <bool> Add(ItemCreateDto item, string email)
        {
            var todo = await _context.Todos
                       .FirstOrDefaultAsync(t => t.Id == item.TodoId &&
                                            t.Author.NormalizedEmail == email.ToLower());

            if (todo == null)
            {
                return(false);
            }

            var newItem = new Item()
            {
                Content = item.Content,
                isDone  = item.IsDone,
                Order   = item.Order,
                TodoId  = item.TodoId
            };

            await _context.Items.AddAsync(newItem);

            var res = await _context.SaveChangesAsync();

            return(res > 0);
        }
Ejemplo n.º 2
0
        public async Task <Guid> CreateItem(ItemCreateDto itemDto, HttpRequest request)
        {
            var item = this.Mapper.Map <Item>(itemDto);

            item.Id        = Guid.NewGuid();
            item.IsActive  = true;
            item.ImagePath = string.Empty;

            if (itemDto.Photo != null && itemDto.Photo.Length > 0)
            {
                var folderName = Path.Combine("resources", "items");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                var fileName  = string.Format($"{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}_{itemDto.Photo.FileName.Trim()}");
                var imagePath = Path.Combine(pathToSave, fileName);

                using (var stream = new FileStream(imagePath, FileMode.Create))
                {
                    item.ImagePath = imagePath;
                    item.ImageUrl  = string.Format($"{GetResourcesItemUri(request)}/{fileName}");

                    await itemDto.Photo.CopyToAsync(stream);
                }
            }

            await this.Repository.AddAsync(item);

            await this.Repository.SaveAsync();

            return(item.Id);
        }
Ejemplo n.º 3
0
        public IActionResult CreateItem(int playerId,
                                        [FromBody] ItemCreateDto item)
        {
            var player = PlayersDataStore.Current.Players.
                         FirstOrDefault(p => p.Id == playerId);

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

            var maxItemId = PlayersDataStore.Current.Players.
                            SelectMany(p => p.Item).Max(i => i.Id);

            var finalItem = new ItemDto()
            {
                Id    = ++maxItemId,
                Name  = item.Name,
                Value = item.Value
            };

            player.Item.Add(finalItem);

            return(CreatedAtRoute(
                       "GetItem",
                       new { playerId, id = finalItem.Id },
                       finalItem
                       ));
        }
Ejemplo n.º 4
0
        public IActionResult CreateItem([FromBody] ItemCreateDto itemCreateDto)
        {
            if (itemCreateDto == null)
            {
                return(BadRequest(ModelState));
            }

            if (_itemRepository.ItemExists(itemCreateDto.Name))
            {
                ModelState.AddModelError("", "Item Exists!");
                return(StatusCode(404, ModelState));
            }

            var itemObj = _mapper.Map <Item>(itemCreateDto);

            if (!_itemRepository.CreateItem(itemObj))
            {
                ModelState.AddModelError("", $"Something went wrong when saving the record {itemObj.Name}");
                return(StatusCode(500, ModelState));
            }


            itemObj = _itemRepository.GetItem(itemObj.Id);
            var itemDto = _mapper.Map <ItemDto>(itemObj);

            return(StatusCode(StatusCodes.Status201Created, itemDto));
        }
        public async Task <IActionResult> CreateAsync([FromBody] ItemCreateDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (createDto.UnitPerBuy == 0)
            {
                return(BadRequest(new { Error = "Unit per buy cannot be null or zero." }));
            }

            if (createDto.UnitPerSell == 0)
            {
                return(BadRequest(new { Error = "Unit per sell cannot be null or zero." }));
            }

            var currentUser = await _userManager.GetUserAsync(HttpContext.User);

            var item = _mapper.Map <Item>(createDto);

            item.CreateUserId     =
                item.UpdateUserId = currentUser?.Id;

            await _unitOfWork.ItemRepository.AddAsync(item);

            await _unitOfWork.CompleteAsync();

            var dto = _mapper.Map <ItemDto>(item);

            return(Ok(dto));
        }
Ejemplo n.º 6
0
        public ActionResult <ItemReadDto> CreateItem(ItemCreateDto itemCreateDto)
        {
            var itemModel = _mapper.Map <Item>(itemCreateDto);

            var items = _repository.GetAllItems();

            foreach (Item itm in items)
            {
                if (itemModel.ItemName == itm.ItemName)
                {
                    return(Ok("This item already exists on the ShoppingList, maybe you just want to update it."));
                }
            }

            if (itemModel.Required == 0)
            {
                itemModel.Required = 1;
            }
            if (itemModel.Required != itemModel.Provided)
            {
                itemModel.Status = false;
            }
            else
            {
                itemModel.Status = true;
            }
            _repository.CreateItem(itemModel);
            _repository.SaveChanges();

            var itemReadDto = _mapper.Map <ItemReadDto>(itemModel);

            //return CreatedAtRoute(nameof(GetItemByName), new {Id = itemReadDto.Id}, itemReadDto);
            return(Ok(itemReadDto));
        }
Ejemplo n.º 7
0
        public async Task <bool> CreateItemAsync(string userId, ItemCreateDto model)
        {
            var item = new Item(userId, model.Name, model.Location);

            await _context.Items.AddAsync(item);

            return(await _context.SaveChangesAsync() == 1);
        }
Ejemplo n.º 8
0
        public ActionResult AddItem(ItemCreateDto itemCreateDto)
        {
            var itemModel = _mapper.Map <Item>(itemCreateDto);

            _repository.AddItem(itemModel);
            _repository.SaveChanges();

            return(Created("Success", itemModel));
        }
Ejemplo n.º 9
0
        public async Task <ActionResult <ItemDto> > Post([FromBody] ItemCreateDto itemCreate)
        {
            Item item = _mapper.Map <Item>(itemCreate);

            _itemGroupRepository.Create(item);
            await _itemGroupRepository.Save();

            return(CreatedAtRoute("GetItemGroup", new { id = item.Id }, item));
        }
        public ActionResult Create(ItemCreateDto itemCreateDto)
        {
            var itemModel = _mapper.Map <Item>(itemCreateDto);

            _itemService.Create(itemModel);
            _itemService.SaveChanges();
            var itemReadFullDto = _mapper.Map <ItemReadFullDto>(itemModel);

            return(CreatedAtRoute(nameof(GetItem), new { id = itemReadFullDto.Id }, itemReadFullDto));
        }
        public ActionResult <ItemReadDto> CreateItem(ItemCreateDto itemCreateDto)
        {
            var itemModel = _mapper.Map <ItemToGetRidOff>(itemCreateDto);

            _repository.CreateItem(itemModel);
            _repository.SaveChanges();

            var itemReadDto = _mapper.Map <ItemReadDto>(itemModel);

            return(CreatedAtRoute(nameof(GetItemById), new { Id = itemReadDto.Id }, itemReadDto));
        }
Ejemplo n.º 12
0
        public async Task <ActionResult <Item> > CreateItem(ItemCreateDto itemCreate)
        {
            var item = _mapper.Map <Item>(itemCreate);

            item.UserId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
            _repo.CreateItem(item);
            var saved = await _repo.SaveChangesAsync();

            var itemRead = _mapper.Map <ItemReadDto>(item);

            return(Created("api/[controller]", itemRead));
        }
Ejemplo n.º 13
0
        public ActionResult <ItemDto> CreateItem(ItemCreateDto itemDto)
        {
            Item item = new() {
                Id          = Guid.NewGuid(),
                Name        = itemDto.Name,
                Price       = itemDto.Price,
                CreatedDate = DateTimeOffset.UtcNow
            };

            _repository.CreateItem(item);

            return(CreatedAtAction(nameof(GetItem), new { id = item.Id }, item.AsDto()));
        }
Ejemplo n.º 14
0
        public async Task <ActionResult <ItemDto> > CreateItemAsync(ItemCreateDto itemDto)
        {
            Item item = new Item()
            {
                Id          = Guid.NewGuid(),
                Name        = itemDto.Name,
                Price       = itemDto.Price,
                CreatedDate = DateTimeOffset.UtcNow
            };

            await repository.CreateItemAsync(item);

            return(CreatedAtAction(nameof(GetItemsAsync), new { id = item.Id }, item.AsDto()));
        }
Ejemplo n.º 15
0
        public async Task <ActionResult <ItemReadDto> > CreateItem([FromBody] ItemCreateDto itemDto)
        {
            Item item = new Item()
            {
                Id        = Guid.NewGuid(),
                Name      = itemDto.Name,
                Price     = itemDto.Price ?? 0,
                UserId    = HttpContext.GetUserId(),
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _itemRepository.CreateItemAsync(item);

            return(CreatedAtAction(nameof(GetItem), new { id = item.Id }, item.AsDto()));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Post(ItemCreateDto item)
        {
            _userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            if (!ModelState.IsValid)
            {
                return(BadRequest("Please submit a valid item"));
            }
            var result = await _itemService.CreateItemAsync(_userId, item);

            if (result)
            {
                return(Ok("Item Created Successfully"));
            }

            throw new System.Exception("Creating the item failed on save");
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Add([FromBody] ItemCreateDto item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string email  = Helper.GetEmail(HttpContext);
            var    result = await _repo.Add(item, email);

            if (result)
            {
                return(Ok(item));
            }

            return(StatusCode(500));
        }
        public async Task CreateItem_WithItemToCreate_ReturnsCreatedItem()
        {
            // Arrange
            var itemToCreate = new ItemCreateDto()
            {
                Name  = Guid.NewGuid().ToString(),
                Price = rand.Next(1000)
            };
            var controller = new ItemsController(itemRepositoryStub.Object);

            // Act
            var result = await controller.CreateItem(itemToCreate);

            // Assert
            var createdResult = Assert.IsType <CreatedAtActionResult>(result.Result);
            var item          = Assert.IsType <ItemReadDto>(createdResult.Value);

            itemToCreate.Should().BeEquivalentTo(item, options => options.ComparingByMembers <ItemCreateDto>().ExcludingMissingMembers());
            item.Id.Should().NotBeEmpty();
        }
        public async Task <IActionResult> AddItemToCustomer(int custId,
                                                            [FromForm] ItemCreateDto itemCreate)
        {
            var customer = await _unitOfWork.Customers.Get(custId);

            if (customer == null)
            {
                return(NotFound());
            }
            var item = _mapper.Map <Item>(itemCreate);

            item.customerId = custId;
            _unitOfWork.Items.Add(item);
            if (await _unitOfWork.Save())
            {
                var itemToReturn = _mapper.Map <ItemDto>(item);
                return(CreatedAtRoute("GetItem", new { item.id }, itemToReturn));
            }
            return(BadRequest("Could not add the item"));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> CreateItem([FromForm] ItemCreateDto itemDto)
        {
            var hasGroup = await GroupApplication.ExistGroup(g => g.Id.Equals(itemDto.GroupId));

            if (!hasGroup)
            {
                ErrorMessage error = new ErrorMessage((int)HttpStatusCode.BadRequest, $"O grupo, {itemDto.GroupId}, não existe.");
                return(BadRequest(error));
            }

            // Check if the item already exists
            bool hasItem = await ItemApplication.ExistItem((i) => i.Name.ToLower().Equals(itemDto.Name.ToLower()));

            if (hasItem)
            {
                ErrorMessage error = new ErrorMessage((int)HttpStatusCode.BadRequest, $"O item, {itemDto.Name}, já existe.");
                return(BadRequest(error));
            }

            var itemId = await ItemApplication.CreateItem(itemDto, Request);

            return(CreatedAtRoute("GetItemById", new { id = itemId }, null));
        }
Ejemplo n.º 21
0
        public ActionResult <ItemReadDto> CreateItem(ItemCreateDto itemCreateDto)
        {
            var model = new Item()
            {
                IdCategory = _repository.GetCategoryById(itemCreateDto.CategoryId),
                ItemName   = itemCreateDto.ItemName,
            };

            try
            {
                _repository.CreateItem(model);
                _repository.SaveChanges();
                _logger.LogInformation("Item created by {HttpUser}", HttpContext.User.Identity.Name);
            }
            catch (System.Exception ex)
            {
                _logger.LogInformation("Item creation failed. Exception:", ex.Message);
            }


            var readDto = _mapper.Map <ItemReadDto>(model);

            return(CreatedAtRoute(nameof(GetItemById), new { Id = readDto.ItemId }, readDto));
        }
Ejemplo n.º 22
0
 public async Task <ItemDto> Create([FromBody] ItemCreateDto dto)
 {
     return(await ItemAppService.CreateAsync(dto));
 }