public async Task <IngredientDto> GetIngredient(int userId, int ingredientId) { var ingredient = new IngredientDto(); string selectCommandText = "dbo.getIngredientByUserId"; SqlParameter parameterUsername = new SqlParameter("@userId", SqlDbType.Int); parameterUsername.Value = userId; SqlParameter parameterIngredientId = new SqlParameter("@ingredientId", SqlDbType.Int); parameterIngredientId.Value = ingredientId; bool isIngredientExist = false; using (SqlDataReader reader = await SqlHelper.ExecuteReaderAsync(conStr, selectCommandText, CommandType.StoredProcedure, parameterUsername, parameterIngredientId)) { while (reader.Read()) { isIngredientExist = true; ingredient.Id = (int)reader["ingredient_id"]; ingredient.Name = (string)reader["ingredient_name"]; ingredient.Description = (string)reader["ingredient_description"]; ingredient.SlugUrl = (string)reader["ingredient_slug"]; } await reader.CloseAsync(); } return(isIngredientExist ? ingredient : null); }
public IHttpActionResult UpdateIngredient(int id, IngredientDto ingredientDto) { var ingredientInDb = _unitOfWork.Ingredients.GetIngredient(id); if (ingredientInDb == null) { return(NotFound()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var ingredient = _mapper.Map <IngredientDto, Ingredient>(ingredientDto); _unitOfWork.Ingredients.UpdateIngredient(ingredientInDb, ingredient); try { _unitOfWork.Complete(); } catch (Exception ex) { return(InternalServerError(ex)); } return(Ok()); }
//Cập nhật Ingredient public async Task <bool> Update(IngredientDto model) { var brand = _mapper.Map <Ingredient>(model); _repoIngredient.Update(brand); return(await _repoIngredient.SaveAll()); }
public IngredientDto ToDto(IngredientDbModel item) { var ingredientDtoToReturn = new IngredientDto { Id = item.Id, CocktailId = item.Id, ComponentId = item.ComponentId, ProportionType = item.ProportionType.ToString(), ProportionValue = item.ProportionValue }; if (item.ProportionType.Equals(ProportionType.Milliliter)) { var drinkDbModel = _context.DrinksSet.Find(item.ComponentId); var drinkDto = _drinkMapper.ToDto(drinkDbModel); ingredientDtoToReturn.Drink = drinkDto; } else { var mealDbModel = _context.MealsSet.Find(item.ComponentId); var mealDto = _mealMapper.ToDto(mealDbModel); ingredientDtoToReturn.Meal = mealDto; } return(ingredientDtoToReturn); }
internal IngredientDto Map(Ingredient ingredient) { var ingredientDto = new IngredientDto(); ingredientDto.Name = ingredient.Name; ingredientDto.Id = ingredient.Id; ingredientDto.Category = new IngredientCategoryDto { Id = ingredient.IngredientCategory.Id, Name = ingredient.IngredientCategory.Name }; ingredientDto.Contributions = new List <ContributionDto>(); ingredientDto.Compounds = new List <CompoundDto>(); foreach (var contribution in ingredient.IngredientContributions) { ingredientDto.Contributions.Add(new ContributionDto { Contribution = contribution.Contribution, Method = MethodAssembler.Map(contribution.ContributionMethod) }); } foreach (var compound in ingredient.IngredientCompounds) { ingredientDto.Compounds.Add(new CompoundDto { Id = compound.Compound.Id, Name = compound.Compound.Name, CasNumber = compound.Compound.CasNumber }); } return(ingredientDto); }
public IngredientDbModel ToDbModel(IngredientDto item) { var proportionType = Enum.TryParse(typeof(ProportionType), item.ProportionType, out var result); if (proportionType) { if (item.Id == 0) { return(new IngredientDbModel { ComponentId = item.ComponentId, CocktailId = item.CocktailId, ProportionType = (ProportionType)result, ProportionValue = item.ProportionValue }); } else { return(new IngredientDbModel { Id = item.Id, ComponentId = item.ComponentId, CocktailId = item.CocktailId, ProportionType = (ProportionType)result, ProportionValue = item.ProportionValue }); } } else { throw new InvalidCastException(nameof(result)); } }
public IngredientDto ActionIngredient(IngredientDto ingredientDto) { Ingredient ingredientEntity = Context.Ingredients .SingleOrDefault(ing => ing.IsValid && ing.Id == ingredientDto.Id); EntityState entityState = EntityState.Modified; if (ingredientEntity == null) { ingredientEntity = new Ingredient() { Name = ingredientDto.Name, Description = ingredientDto.Description }; entityState = EntityState.Added; } else { ingredientEntity.Name = ingredientEntity.Name; ingredientEntity.Description = ingredientEntity.Description; } Context.Entry(ingredientEntity).State = entityState; Context.SaveChanges(); ingredientDto.Id = ingredientEntity.Id; return(ingredientDto); }
public IActionResult AddIngredientToFood(Guid foodId, [FromBody] IngredientDto ingredient) { if (ingredient == null) { return(BadRequest()); } FoodItem foodItem = _foodRepository.GetSingle(foodId); if (foodItem == null) { return(NotFound("FoodNotFound")); } var ingredientModel = _mapper.Map <Ingredient>(ingredient); ingredientModel.FoodItem = foodItem; _repository.Add(ingredientModel); if (!_repository.Save()) { throw new Exception($"Creating a ingredients for food {foodId} failed on save."); } var ingredientToReturn = _mapper.Map <IngredientDto>(ingredientModel); _hubContext.Clients.All.SendAsync("ingredient-added", foodId, ingredientToReturn); return(CreatedAtRoute(nameof(GetSingleIngredient), new { foodId = foodId, id = ingredientToReturn.Id }, ingredientToReturn)); }
public async Task <List <IngredientDto> > GetIngredients(int userId) { List <IngredientDto> ingredients = new List <IngredientDto>(); string selectCommandText = "dbo.getIngredientsByUserId"; SqlParameter parameterUserId = new SqlParameter("@userId", SqlDbType.Int); parameterUserId.Value = userId; using (SqlDataReader reader = await SqlHelper.ExecuteReaderAsync(conStr, selectCommandText, CommandType.StoredProcedure, parameterUserId)) { while (reader.Read()) { var ingredient = new IngredientDto { Id = (int)reader["ingredient_id"], Name = (string)reader["ingredient_name"], Description = (string)reader["ingredient_description"], SlugUrl = (string)reader["ingredient_slug"], }; ingredients.Add(ingredient); } await reader.CloseAsync(); } return(ingredients); }
public async Task <int> Update(int userId, int ingredientId, IngredientDto ingredient) { try { string updateCommandText = @"UPDATE Ingredients SET IngredientName = @name, IngredientDescription = @description WHERE IngredientId = @ingredientId AND UserId = @userId"; SqlParameter ingredient_name = new SqlParameter("@name", ingredient.Name); SqlParameter ingredient_description = new SqlParameter("@description", ingredient.Description); SqlParameter ingredient_id = new SqlParameter("@ingredientId", ingredientId); SqlParameter user_id = new SqlParameter("@userId", userId); Int32 rows = await SqlHelper.ExecuteNonQueryAsync(conStr, updateCommandText, CommandType.Text, ingredient_name, ingredient_description, ingredient_id, user_id); return(rows >= 1 ? rows : 0); } catch (System.Exception) { throw new Exception("Problem saving changes"); } }
public async Task CreateCorrect_Ingredient() { //Arrange var options = TestUtilities.GetOptions(nameof(CreateCorrect_Ingredient)); var mapper = new Mock <IDtoMapper <Ingredient, IngredientDto> >(); var mockDateTimeProvider = new Mock <IDateTimeProvider>(); var ingredientDto = new IngredientDto { Name = "Cola" }; mapper.Setup(x => x.MapDto(It.IsAny <Ingredient>())).Returns(ingredientDto); using (var assertContext = new CocktailMagicianContext(options)) { //Act & Assert var sut = new IngredientService(assertContext, mapper.Object, mockDateTimeProvider.Object); var result = await sut.CreateIngredientAsync(ingredientDto); Assert.IsInstanceOfType(result, typeof(IngredientDto)); Assert.AreEqual(0, result.Id); Assert.AreEqual("Cola", result.Name); } }
public List <IngredientDto> GetIngredients(int count, int skipIndex) { var ingredients = _collection.AsQueryable <Ingredient>(); ingredients = ingredients.Skip(skipIndex * count).Take(count); var ingredientDtos = new List <IngredientDto>(); foreach (var ingredient in ingredients) { var ingredientDto = new IngredientDto { IngredientId = ingredient._id.ToString(), Name = ingredient.Name, Description = ingredient.Description, CarbonHydrateWeightPercent = ingredient.CarbonHydrateWeightPercent, EnergyInKcal = ingredient.EnergyInKcal, FatWeightPercent = ingredient.FatWeightPercent, ProteineWeightPercent = ingredient.ProteineWeightPercent, AlcoholVolumePercent = ingredient.AlcoholVolumePercent }; ingredientDtos.Add(ingredientDto); } return(ingredientDtos); }
public IngredientDto ActionIngredient(IngredientDto ingredientDto) { try { var ingredientEntity = GetSingleOrDefaultBaseEntity(ingredientDto.Id, true); EntityState entityState = EntityState.Modified; if (ingredientEntity is null) { ingredientEntity = new Ingredient() { Name = ingredientDto.Name, Description = ingredientDto.Description, IngredientType = ingredientDto.IngredientType, }; entityState = EntityState.Added; }//Add case else { ingredientEntity.Name = ingredientDto.Name; ingredientEntity.Description = ingredientDto.Description; ingredientEntity.IngredientType = ingredientDto.IngredientType; }//Update case Context.Entry(ingredientEntity).State = entityState; Context.SaveChanges(); ingredientDto.Id = ingredientEntity.Id; return(ingredientDto); } catch (Exception) { return(null); } }
public List <IngredientDto> GetAllIngredients() { var ingredients = _collection.FindAllAs <Ingredient>(); var ingredientDtos = new List <IngredientDto>(); foreach (var ingredient in ingredients) { var ingredientDto = new IngredientDto { IngredientId = ingredient._id.ToString(), Name = ingredient.Name, Description = ingredient.Description, CarbonHydrateWeightPercent = ingredient.CarbonHydrateWeightPercent, EnergyInKcal = ingredient.EnergyInKcal, FatWeightPercent = ingredient.FatWeightPercent, ProteineWeightPercent = ingredient.ProteineWeightPercent, AlcoholVolumePercent = ingredient.AlcoholVolumePercent }; ingredientDtos.Add(ingredientDto); } return(ingredientDtos); }
public async Task <Unit> Handle(UpdateIngredientCommand request, CancellationToken cancellationToken) { var user = await _userAuth.GetUser(request.Username); if (user == null) { throw new RestException(HttpStatusCode.Unauthorized, new { User = "******" }); } var ingredent = await _ingredientGenerator.GetIngredient(user.Id, request.IngredientId); if (ingredent == null) { throw new RestException(HttpStatusCode.NotFound, new { Ingredent = "Not found" }); } var updateIngredent = new IngredientDto { Name = request.Name ?? ingredent.Name, Description = request.Description ?? ingredent.Description }; var success = await _ingredientGenerator.Update(user.Id, request.IngredientId, updateIngredent); if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
public static Ingredient NewFromPOCO(IngredientDto ing) { return(new Ingredient() { Name = ing.Name }); }
public virtual HttpResponseMessage Get(Guid id) { Ingredient ingredient = ingredientService.Get(id); IngredientDto ingredientDto = AutoMapper.Map <Ingredient, IngredientDto>(ingredient); return(Request.CreateResponse(HttpStatusCode.OK, ingredientDto)); }
public void AddShopListItem() { // Arrage IDataAccessObjectFactory factory = DatabaseFactory.GetInstance(); IDataAccessObject database = factory.GetDao(); var item = new IngredientDto() { Amount = 3, IngredientName = "Test", Unit = "Test" }; // Act database.AddShopListItem("db1500c7-f616-45d3-8069-14a9f264f2fa", item); // Assert var list = database.GetShopList("db1500c7-f616-45d3-8069-14a9f264f2fa"); foreach (var i in list) { if (i.IngredientName == "Test") { database.DeleteRecipe("Test"); Assert.Pass(); } } Assert.Fail(); }
public IHttpActionResult AddIngredient([FromBody] IngredientDto ingredient) { if (!ModelState.IsValid) { return(BadRequest("validation failed")); } try { using (var db = new ApplicationDbContext()) { if (db.Ingredients.Where(x => x.Name.Equals(ingredient.Name)).Any()) { return(BadRequest("המצרך כבר קיים במערכת")); } var ingr = new Ingredient() { Description = ingredient.Description, Name = ingredient.Name, }; db.Ingredients.Add(ingr); db.SaveChanges(); ingredient.Id = ingr.Id; return(Ok(ingredient)); } } catch (Exception e) { return(InternalServerError(e)); } }
public async Task CorrectlyCreateIngredient() { //Arrange var options = TestUtilities.GetOptions(nameof(CorrectlyCreateIngredient)); var mapperMock = new Mock <IDtoMapper <Ingredient, IngredientDto> >(); var testGuid = Guid.NewGuid(); var entityDto = new IngredientDto { Id = testGuid, Name = "djodjan", }; var ingredientDto = new IngredientDto { Id = testGuid, Name = "djodjan", }; mapperMock.Setup(x => x.MapFrom(It.IsAny <Ingredient>())).Returns(ingredientDto); using (var assertContext = new CWContext(options)) { //Act & Assert var sut = new IngredientService(assertContext, mapperMock.Object); var result = await sut.CreateIngredientAsync(entityDto); Assert.IsInstanceOfType(result, typeof(IngredientDto)); Assert.AreEqual("djodjan", result.Name); Assert.AreEqual(entityDto.Name, result.Name); } }
public void UpsertIngredient(IngredientDto ingredient) { try { if (ingredient.IngredientId == null) { ingredient.IngredientId = "000000000000000000000000"; } var ingredientEntity = new Ingredient { _id = new ObjectId(ingredient.IngredientId), Name = ingredient.Name, Description = ingredient.Description, CarbonHydrateWeightPercent = ingredient.CarbonHydrateWeightPercent, EnergyInKcal = ingredient.EnergyInKcal, FatWeightPercent = ingredient.FatWeightPercent, ProteineWeightPercent = ingredient.ProteineWeightPercent, AlcoholVolumePercent = ingredient.AlcoholVolumePercent }; _collection.Save(ingredientEntity); } catch (Exception e) { throw new Exception("Failed to insert new ingredient in database", e); } }
public static Ingredient FromPOCO(IngredientDto ing) { return(new Ingredient() { ID = ing.ID, Name = ing.Name }); }
public async Task UpdateAsync(IngredientDto entity) { await MongoDbContext .GetCollection <IngredientDto>() .ReplaceOneAsync(i => i.Id == entity.Id, entity); await UpdateIngredientInRestaurants(entity); }
public async Task AddAsync(IngredientDto entity) { await MongoDbContext .GetCollection <IngredientDto>() .InsertOneAsync(entity); await AddIngredientInRestaurants(entity); }
private async Task <Ingredient> updateIngredient(Ingredient ingredient, IngredientDto updatedIngredient) { ingredient.Name = updatedIngredient.Name; ingredient.Amount = updatedIngredient.Amount; ingredient.Unit = updatedIngredient.Unit; _context.Ingredients.Update(ingredient); return(ingredient); }
public ActionResult UpdateIngredient(IngredientDto ingredient) { if (ingredient.Id != 0) { _ingredientRepository.UpdateIngredient(ingredient); } return(Json(new { success = true, responseText = "Updated sucessfully!" }, JsonRequestBehavior.AllowGet)); }
//Thêm Ingredient mới vào bảng Ingredient public async Task <bool> Add(IngredientDto model) { var ingredient = _mapper.Map <Ingredient>(model); ingredient.isShow = true; _repoIngredient.Add(ingredient); return(await _repoIngredient.SaveAll()); }
// PUT /api/<controller>/5 public IngredientDto Put(int id, IngredientDto IngredientDto) { var IngredientAlterar = _IngredientServico.GetById(id); IngredientAlterar.Name = IngredientDto.Name; _IngredientServico.Save(IngredientAlterar); return(IngredientDto); }
public void ToIngredientDto_IngredientWithEmptyFields_IngredientDtoIsEqualToIngredient() { Ingredient ingredient = new Ingredient(); IngredientDto result = DtoBuilder.ToDto(ingredient); base.AssertIngredientsAreEqual(ingredient, result); }
public void UpdateIngredient(IngredientDto ingredientDto) { var ingredient = ingredientRepository.GetBy(ingredientDto.Id); ingredientDto.MappingIngredient(ingredient); ingredientRepository.Update(ingredient); }