public IHttpActionResult Criar([FromBody] ItemModel obj)
        {
            try
            {
                if (obj == null || String.IsNullOrWhiteSpace(obj.Nome) || String.IsNullOrWhiteSpace(obj.Descricao))
                {
                    return(ResponseMessage(Request.CreateResponse <string>(HttpStatusCode.NotAcceptable, "Necessário informar os campos: Nome e Descricao.")));
                }

                try
                {
                    Item item = new Item(obj.Nome, obj.Descricao);

                    _itemRepository.AddAsync(item);

                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Created)));
                }
                catch (Exception erro)
                {
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotModified)));
            }
            catch (Exception erro)
            {
                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, "Ocorreu um erro ao tentar processar a requisição.")));
            }
        }
        public async Task <ItemDto> Handle(AddItemCommand command, CancellationToken cancellationToken)
        {
            var itemFromCommand = _mapper.Map <Item>(command);

            // Just for demo to show that Dapr Store working!
            //var oldItem = await _daprClient.GetStateAsync<Item>("default", itemFromCommand.ItemId.ToString(), cancellationToken: cancellationToken);

            var itemFromDb = await _itemRepository.GetAsync(itemFromCommand.ItemId, cancellationToken);

            if (itemFromDb != null)
            {
                _mapper.Map(itemFromCommand, itemFromDb);
                _itemRepository.Update(itemFromDb);
            }
            else
            {
                await _itemRepository.AddAsync(itemFromCommand, cancellationToken);
            }

            await _itemRepository.SaveChangesAsync(cancellationToken);

            //await _basketItemNotificationHandler.Handle(new BasketItemCreatedMessage(), cancellationToken);

            return(_mapper.Map <ItemDto>(itemFromCommand));
        }
        public async Task <CreateItemCommandResponse> Handle(CreateItemCommand request, CancellationToken cancellationToken)
        {
            var createItemCommandResponse = new CreateItemCommandResponse();

            var validator        = new CreateItemCommandValidator();
            var validationResult = await validator.ValidateAsync(request);


            if (validationResult.Errors.Count > 0)
            {
                createItemCommandResponse.Success          = false;
                createItemCommandResponse.ValidationErrors = new List <string>();
                foreach (var error in validationResult.Errors)
                {
                    createItemCommandResponse.ValidationErrors.Add(error.ErrorMessage);
                }
            }
            if (createItemCommandResponse.Success)
            {
                var item = _mapper.Map <Item>(request);
                item = await _itemRepository.AddAsync(item);

                createItemCommandResponse.Item = _mapper.Map <CreateItemDto>(item);
            }

            return(createItemCommandResponse);
        }
Esempio n. 4
0
        public async Task <Item> Adicionar(Item item, CancellationToken ct)
        {
            await _itemRepository.AddAsync(item, ct);

            await _unitOfWork.CommitAsync(ct);

            return(item);
        }
        public async Task <IActionResult> Get()
        {
            Item item = Item.CreateNew(1, null);
            await itemRepository.AddAsync(item);

            await itemRepository.SaveAsync();

            return(Ok());
        }
Esempio n. 6
0
        public async Task PostNewItem_InvalidItem_BadRequestReturned()
        {
            _itemCreator.SetItem(FakeItem).Returns(FakeItem);
            _repository.AddAsync(FakeItem).Returns(Task.FromResult(FakeItem));

            var response = await _controller.ResolveAction(controller => controller.PostAsync(FakeItem)).BeItReducedResponse <Item>();

            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
        }
Esempio n. 7
0
        public async Task TestAddItemAsync()
        {
            var id = await _itemRepository.AddAsync(new ConsoleApp.Models.Item
            {
                Id    = 1,
                Title = "TestTitle"
            });

            Assert.AreEqual(id, 1);
        }
Esempio n. 8
0
        public async Task HandleAsync(ItemCreated1 @event)
        {
            await _repository.AddAsync(new xItem
            {
                Id     = @event.Id,
                Item   = @event.Item,
                Status = @event.Status,
                Count  = @event.Count
            });

            _logger.LogInformation($"Item created: {@event.Item}");
        }
        public async Task Add(ItemCreateRequest request, int gameId)
        {
            var item = new Item
            {
                Name        = request.Name,
                Description = request.Description,
                ImageLink   = request.ImageLink,
                GameId      = gameId
            };

            await _itemRepository.AddAsync(item);
        }
Esempio n. 10
0
        public Task AddItemAsync(IItemConfiguration itemConfiguration)
        {
            if (_itemRepository.Any(x => x.Name == itemConfiguration.Name))
            {
                Log.Warn($"Item with name '{itemConfiguration.Name}' already exists");
                return(Task.CompletedTask);
            }

            var item = _itemBuilder.Build(itemConfiguration);

            return(_itemRepository.AddAsync(item));
        }
Esempio n. 11
0
        public async Task <IActionResult> Post([FromBody] AddItemViewModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            var parentItem = await _itemGroupRepo.GetAsync(model.ItemGroupId);

            if (parentItem == null)
            {
                return(NotFound(Resources.Items.ItemResource.ItemGroupNotFound));
            }

            var unit = await _unitRepo.GetAsync(model.UnitId);

            if (unit == null)
            {
                return(NotFound(Resources.Items.ItemResource.UnitNotFound));
            }

            if (await _itemRepo.IsExistCodeAsync(model.Code))
            {
                ModelState.AddModelError("Code", Resources.Global.Common.ThisCodeExist);
            }
            if (await _itemRepo.IsExistNameAsync(model.Name))
            {
                ModelState.AddModelError("Name", Resources.Global.Common.ThisNameExist);
            }

            if (!string.IsNullOrWhiteSpace(model.UnitBarcode) && await _itemUnitRepo.IsExistCodeAsync(model.UnitBarcode))
            {
                ModelState.AddModelError("UnitBarcode", Resources.Items.ItemResource.ThisBarCodeExist);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetWithErrorsKey()));
            }

            var item = new Item(model.Name, model.Code, model.Type, parentItem.Id, true, model.Note, unit.Id, model.UnitBarcode);

            var affectedRows = await _itemRepo.AddAsync(item);

            if (affectedRows > 0)
            {
                var viewModel = AutoMapper.Mapper.Map <ItemViewModel>(item);

                return(CreatedAtRoute("GetItem", new { id = item.Number }, viewModel));
            }
            return(BadRequest());
        }
Esempio n. 12
0
        public async Task <Unit> Handle(CreateStockItemCommand request, CancellationToken cancellationToken)
        {
            if (await _repository.ExistsAsync(request.Id))
            {
                throw new ItemAlreadyExistsException(request.Id);
            }
            var item = Domain.Entities.Item.Create(request.Id, request.Amount);
            await _repository.AddAsync(item);

            await _eventProcessor.ProcessAsync(item.Events);

            return(Unit.Value);
        }
Esempio n. 13
0
        public async Task <ItemResponse> AddItemAsync(CreateItemRequest request)
        {
            var item = new Item()
            {
                ItemName        = request.ItemName,
                ItemDescription = request.ItemDescription,
                Reviews         = new List <Review>()
            };

            var created = await _itemRepository.AddAsync(item);

            return(MapItemToResponse(created));
        }
Esempio n. 14
0
        public async Task <Unit> Handle(CreateItemCommand request, CancellationToken cancellationToken)
        {
            if (await _repository.ExistsAsync(request.Id))
            {
                throw new ItemAlreadyExistsException(request.Id);
            }
            request.Id = request.Id == Guid.Empty ? Guid.NewGuid() : request.Id;
            var item = Item.Create(request.Id, request.Category, request.Name, request.Description, request.Tags, request.UnitPrice);
            await _repository.AddAsync(item);

            await _eventProcessor.ProcessAsync(item.Events);

            return(Unit.Value);
        }
        public async Task <IHttpActionResult> PostAsync(Item item)
        {
            if (!item.IsValidForCreating())
            {
                return(BadRequest());
            }

            var newItem = _itemCreator.SetItem(item);

            await _repository.AddAsync(newItem);

            var location = _urlGenerator.GetItemUrl(newItem.Id);

            return(Created(location, newItem));
        }
Esempio n. 16
0
        public async Task <ItemResponse> SaveAsync(Item item)
        {
            try
            {
                await _itemRepository.AddAsync(item);

                await _unitOfWork.CompleteAsync();

                return(new ItemResponse(item));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new ItemResponse($"An error occurred when saving the item: {ex.Message}"));
            }
        }
        protected override async Task ValidateAndSave()
        {
            MBovisAnimalExposure.SetValidationContext(Notification);
            MBovisAnimalExposure.NotificationId = NotificationId;
            MBovisAnimalExposure.DobYear        = Notification.PatientDetails.Dob?.Year;

            if (TryValidateModel(MBovisAnimalExposure, nameof(MBovisAnimalExposure)))
            {
                if (RowId == null)
                {
                    await _mBovisAnimalExposureRepository.AddAsync(MBovisAnimalExposure);
                }
                else
                {
                    MBovisAnimalExposure.MBovisAnimalExposureId = RowId.Value;
                    await _mBovisAnimalExposureRepository.UpdateAsync(Notification, MBovisAnimalExposure);
                }
            }
        }
Esempio n. 18
0
        public async Task <ItemDto> Handle(AddItemCommand command, CancellationToken cancellationToken)
        {
            var itemFromCommand = _mapper.Map <Item>(command);

            // Just for demo to show that Dapr Store working!
            //var oldItem = await _daprClient.GetStateAsync<Item>("default", itemFromCommand.ItemId.ToString(), cancellationToken: cancellationToken);

            var basket = await _basketRepository.GetBasketSingeOrDefault(command.Username, cancellationToken);

            var isBasketNotExits = (basket == null);

            if (isBasketNotExits)
            {
                basket = new Domain.Basket {
                    BasketId = Guid.NewGuid(), Username = command.Username, State = State.Unlocked
                };
                await _basketRepository.AddAsync(basket, cancellationToken);

                await _basketRepository.SaveChangesAsync(cancellationToken);
            }

            var itemFromDb = await _itemRepository.GetSingleOrDefault(itemFromCommand.ItemId, cancellationToken);

            itemFromCommand.BasketId = basket.BasketId;
            itemFromCommand.Basket   = basket;

            if (itemFromDb == null)
            {
                await _itemRepository.AddAsync(itemFromCommand, cancellationToken);

                await _itemRepository.SaveChangesAsync(cancellationToken);
            }

            //await _basketItemNotificationHandler.Handle(new ItemCreatedMessage(), cancellationToken);

            //// Lock
            //await _daprClient.SaveStateAsync(
            //    "default",
            //    State.Locked.ToString(), ConsistencyMode.Strong,new StateOptions(),
            //    cancellationToken: cancellationToken);

            return(_mapper.Map <ItemDto>(itemFromCommand));
        }
        protected override async Task ValidateAndSave()
        {
            MBovisUnpasteurisedMilkConsumption.SetValidationContext(Notification);
            MBovisUnpasteurisedMilkConsumption.NotificationId = NotificationId;
            MBovisUnpasteurisedMilkConsumption.DobYear        = Notification.PatientDetails.Dob?.Year;

            if (TryValidateModel(MBovisUnpasteurisedMilkConsumption, nameof(MBovisUnpasteurisedMilkConsumption)))
            {
                if (RowId == null)
                {
                    await _mBovisUnpasteurisedMilkConsumptionRepository.AddAsync(MBovisUnpasteurisedMilkConsumption);
                }
                else
                {
                    MBovisUnpasteurisedMilkConsumption.MBovisUnpasteurisedMilkConsumptionId = RowId.Value;
                    await _mBovisUnpasteurisedMilkConsumptionRepository.UpdateAsync(Notification,
                                                                                    MBovisUnpasteurisedMilkConsumption);
                }
            }
        }
        protected override async Task ValidateAndSave()
        {
            TestResultForEdit.SetValidationContext(Notification);
            TestResultForEdit.NotificationId = NotificationId;
            TestResultForEdit.Dob            = Notification.PatientDetails.Dob;
            await SetRelatedEntitiesAsync();

            SetDate();

            if (TryValidateModel(TestResultForEdit, "TestResultForEdit"))
            {
                if (RowId == null)
                {
                    await _testResultsRepository.AddAsync(TestResultForEdit);
                }
                else
                {
                    TestResultForEdit.ManualTestResultId = RowId.Value;
                    await _testResultsRepository.UpdateAsync(Notification, TestResultForEdit);
                }
            }
        }
Esempio n. 21
0
        protected override async Task ValidateAndSave()
        {
            UpdateFlags();
            MBovisExposureToKnownCase.SetValidationContext(Notification);
            MBovisExposureToKnownCase.NotificationId = NotificationId;
            MBovisExposureToKnownCase.DobYear        = Notification.PatientDetails.Dob?.Year;

            ValidateExposureNotification();

            if (TryValidateModel(MBovisExposureToKnownCase, nameof(MBovisExposureToKnownCase)))
            {
                if (RowId == null)
                {
                    await _mBovisExposureToKnownCasesRepository.AddAsync(MBovisExposureToKnownCase);
                }
                else
                {
                    MBovisExposureToKnownCase.MBovisExposureToKnownCaseId = RowId.Value;
                    await _mBovisExposureToKnownCasesRepository.UpdateAsync(Notification, MBovisExposureToKnownCase);
                }
            }
        }
Esempio n. 22
0
        protected async Task ValidateAndSave(T model, string modelName)
        {
            model.NotificationId = NotificationId;
            model.Dob            = Notification.PatientDetails.Dob;
            SetDates(model, modelName);
            model.SetValidationContext(Notification);

            if (TryValidateModel(model, modelName))
            {
                if (RowId == null)
                {
                    await _socialContextRepository.AddAsync(model);

                    await _alertService.AutoDismissAlertAsync <DataQualityClusterAlert>(Notification);
                }
                else
                {
                    model.Id = RowId.Value;
                    await _socialContextRepository.UpdateAsync(Notification, model);
                }
            }
        }
Esempio n. 23
0
        public async Task <IActionResult> Post(int listId, [FromBody] ReceiveItemViewModel receiveItemViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var list = await _listRepository.GetListById(listId);

            if (list == null)
            {
                return(BadRequest("List does not exist."));
            }

            await _itemRepository.AddAsync(receiveItemViewModel, list.Id);

            _itemRepository.CommitChanges();

            _logger.LogInfo($"New Item was created for list {list.Id}.");

            return(Ok($"New Item was created for list {list.Id}."));
        }
Esempio n. 24
0
        public async Task Run()
        {
            Console.WriteLine("Hello DataRepo!");
            await _sqliteService.InitializeAsync("DataRepo.ConsoleApp");

            var title = string.Empty;

            while (string.IsNullOrEmpty(title))
            {
                Console.Write("Insert title: ");
                title = Console.ReadLine();
            }

            var item = new Models.Item
            {
                Title = title
            };

            await _itemRepository.AddAsync(item);

            var items = await _itemRepository.GetAllAsync();

            items?.ToList().ForEach(x => Console.WriteLine(x));
        }
Esempio n. 25
0
        public async Task <ItemResponse> CreateItem(CreateItemRequest item)
        {
            await _itemRepository.AddAsync(_mapper.Map <Item>(item));

            return(_mapper.Map <ItemResponse>(item));
        }
Esempio n. 26
0
        public async Task AddAsync(ItemAddModel model)
        {
            await _repository.AddAsync(ItemFactory.Create(model, _userId));

            await _unitOfWork.SaveChangesAsync();
        }
 public async Task AddAsync(Guid id, string item, string status, int count)
 {
     var xItem = new xItem(id, item, "open", 1);
     await _repository.AddAsync(xItem);
 }