Ejemplo n.º 1
0
        public HttpResponseMessage Post([FromBody] FoodDTO foodDTO)
        {
            var currentTime = TimeHelper.UnixMsNow;

            foodDTO.CreateUserId = currentUserId;
            foodDTO.CreationTime = currentTime;

            foreach (ServingDTO serving in foodDTO.Servings.Serving)
            {
                serving.CreateUserId = currentUserId;
                serving.CreationTime = currentTime;
            }

            try
            {
                var food = Mapper.Map <Food>(foodDTO);

                unitOfWork.FoodRepository.Insert(food);
                unitOfWork.Save();

                //Преобразовываем обратно, чтобы вернуть клиенту
                foodDTO = Mapper.Map <FoodDTO>(food);
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
            //response.Headers.Location = new Uri("/api/food/" + foodDTO.foodId);

            return(Request.CreateResponse(HttpStatusCode.Created, foodDTO));
        }
Ejemplo n.º 2
0
        public FoodDTO UpdateDTO(FoodDTO dto, int?updateBy)
        {
            if (dto != null)
            {
                dto.FoodId                  = this.FoodId;
                dto.Name                    = this.Name;
                dto.Quantity                = this.Quantity;
                dto.FoodTemplateId          = this.FoodTemplateId;
                dto.SpecificObservations    = this.SpecificObservations;
                dto.Location                = this.Location;
                dto.Progress                = this.Progress;
                dto.Expired                 = this.Expired;
                dto.Liquid                  = this.Liquid;
                dto.Rating                  = this.Rating;
                dto.FeedbackFromBeneficiary = this.FeedbackFromBeneficiary;
                dto.DeliveredBy             = this.DeliveredBy;
                dto.DeliveredTo             = this.DeliveredTo;
                dto.OrderDateTime           = this.OrderDateTime;
                dto.CookedDateTime          = this.CookedDateTime;
                dto.PickupDateTime          = this.PickupDateTime;
                dto.StorageDateTime         = this.StorageDateTime;
                dto.DeliveryDateTime        = this.DeliveryDateTime;
                dto.Active                  = this.Active;
                dto.IsDeleted               = this.IsDeleted;

                dto.UpdateBy = updateBy;
                dto.UpdateOn = System.DateTime.UtcNow;
            }

            return(dto);
        }
Ejemplo n.º 3
0
        public ActionResult <FoodsDTO> GetAllFoods(string name = "")
        {
            using (var db = new SqliteContext())
            {
                try
                {
                    var foods = db.Foods.Where(x => x.Name.ToLower().Contains(name.ToLower()));

                    var dto = new FoodsDTO();
                    dto.FoodList = new List <FoodDTO>();

                    foreach (var food in foods)
                    {
                        var entry = new FoodDTO
                        {
                            Id                 = food.Id,
                            Name               = food.Name,
                            ServingSize        = food.ServingSize,
                            ProteinAmount      = food.ProteinAmount,
                            FatAmount          = food.FatAmount,
                            CarbohydrateAmount = food.CarbohydrateAmount,
                            Calories           = food.Calories,
                        };

                        dto.FoodList.Add(entry);
                    }

                    return(dto);
                }
                catch (ArgumentOutOfRangeException)
                {
                    return(StatusCode(404));
                }
            }
        }
        public List <FoodDTO> PrintFood()
        {
            try
            {
                PlayerDTO pDTO = HttpContext.Session.GetObject <PlayerDTO>("player");
                if (pDTO != null)
                {
                    List <FoodDTO> list = new List <FoodDTO>();
                    foreach (Food f in context.Foods)
                    {
                        FoodDTO ff = new FoodDTO(f, f.FoodNavigation);
                        list.Add(ff);
                    }

                    Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
                    return(list);
                }

                else
                {
                    Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
                    return(null);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Ejemplo n.º 5
0
 public FoodViewModel(FoodDTO t, string editUrl)
 {
     FoodId                  = t.FoodId;
     Name                    = t.Name;
     Quantity                = t.Quantity;
     FoodTemplateId          = t.FoodTemplateId;
     SpecificObservations    = t.SpecificObservations;
     Location                = t.Location;
     Progress                = t.Progress;
     Expired                 = t.Expired;
     Liquid                  = t.Liquid;
     Rating                  = t.Rating;
     FeedbackFromBeneficiary = t.FeedbackFromBeneficiary;
     DeliveredBy             = t.DeliveredBy;
     DeliveredTo             = t.DeliveredTo;
     OrderDateTime           = t.OrderDateTime;
     CookedDateTime          = t.CookedDateTime;
     PickupDateTime          = t.PickupDateTime;
     StorageDateTime         = t.StorageDateTime;
     DeliveryDateTime        = t.DeliveryDateTime;
     Active                  = t.Active;
     IsDeleted               = t.IsDeleted;
     CreateBy                = t.CreateBy;
     CreateOn                = t.CreateOn;
     UpdateBy                = t.UpdateBy;
     UpdateOn                = t.UpdateOn;
     EditUrl                 = editUrl;
 }
Ejemplo n.º 6
0
        public FoodDTO GetFood(int foodId)
        {
            try
            {
                //Requires.NotNegative("foodId", foodId);

                log.Debug("foodId: " + foodId + " ");

                // get
                R_Food t = Repository.GetFood(foodId);

                FoodDTO dto = new FoodDTO(t);

                log.Debug(FoodDTO.FormatFoodDTO(dto));

                return(dto);
            }
            catch (System.Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }
        }
Ejemplo n.º 7
0
 public ThemMon()
 {
     InitializeComponent();
     PathImg       = "";
     ImgStrDefault = Convert.ToBase64String(MONAN.Ins.converImgToByte(@"..\..\images\food.png"));
     food          = new FoodDTO();
 }
Ejemplo n.º 8
0
        public ActionResult <FoodDTO> CreateFood(FoodDTO model)
        {
            try
            {
                var foodCategory = _repository.GetFoodCategoryByID(model.FoodTypeID);
                if (foodCategory == null)
                {
                    return(BadRequest("Food Category could not be find"));
                }

                IMapper mapper  = EDeliveryProfile.CreateFood();
                var     newFood = mapper.Map <Food>(model);

                var userIdClaim = User.FindFirst("MemberId")?.Value;
                var memberId    = int.TryParse(userIdClaim, out var id) ? id : 0;

                EDeliveryDBContext dBContext = new EDeliveryDBContext();

                var restaurantId = dBContext.Restaurant.First(o => o.MemberId == memberId).RestaurantId;
                newFood.RestaurantId = restaurantId;

                _repository.CreateFood(newFood);

                return(new ObjectResult(new { message = "success", statusCode = HttpStatusCode.OK, response = "Created food" }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to create new food:{ex}");
                return(BadRequest("Failed to create new food"));
            }
        }
Ejemplo n.º 9
0
        public int AddFood(FoodDTO dto)
        {
            int id = 0;

            try
            {
                log.Debug(FoodDTO.FormatFoodDTO(dto));

                R_Food t = FoodDTO.ConvertDTOtoEntity(dto);

                // add
                id         = Repository.AddFood(t);
                dto.FoodId = id;

                log.Debug("result: 'success', id: " + id);
            }
            catch (System.Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }

            return(id);
        }
Ejemplo n.º 10
0
        public void GetFoodsPaged_Success_Test()
        {
            // Arrange
            string searchTerm = "";
            int    pageIndex  = 0;
            int    pageSize   = 10;

            // list
            IList <R_Food> list = new List <R_Food>();

            for (int i = 1; i <= pageSize; i++)
            {
                list.Add(SampleFood(i));
            }

            // create mock for repository
            var mock = new Mock <IFoodRepository>();

            mock.Setup(s => s.GetFoods(Moq.It.IsAny <string>(), Moq.It.IsAny <int>(), Moq.It.IsAny <int>())).Returns(list);

            // service
            FoodService foodService = new FoodService();

            FoodService.Repository = mock.Object;

            // Act
            var     resultList = foodService.GetFoods(searchTerm, pageIndex, pageSize);
            FoodDTO result     = resultList.FirstOrDefault();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.FoodId);
            Assert.AreEqual(10, resultList.Count);
        }
Ejemplo n.º 11
0
        public void GetFoods_Success_Test()
        {
            // Arrange
            R_Food food = SampleFood(1);

            IList <R_Food> list = new List <R_Food>();

            list.Add(food);

            // create mock for repository
            var mock = new Mock <IFoodRepository>();

            mock.Setup(s => s.GetFoods()).Returns(list);

            // service
            FoodService foodService = new FoodService();

            FoodService.Repository = mock.Object;

            // Act
            var     resultList = foodService.GetFoods();
            FoodDTO result     = resultList.FirstOrDefault();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.FoodId);
        }
Ejemplo n.º 12
0
        private void txtFoodID_TextChanged(object sender, EventArgs e)
        {
            int     foodId     = Convert.ToInt32(txtFoodID.Text.Trim());
            FoodDTO categoryId = FoodDAO.Instance.GetCategoryIDByFoodID(foodId);

            if (categoryId != null)
            {
                CategoryDTO cate = CategoryDAO.Instance.GetCategoryByID(categoryId.IdCate);
                if (cate != null)
                {
                    int index = -1;
                    int i     = 0;
                    foreach (CategoryDTO item in cbFoodCategory.Items)
                    {
                        if (item.Id == cate.Id)
                        {
                            index = i;
                            break;
                        }
                        i++;
                    }

                    cbFoodCategory.SelectedIndex = index;
                }
            }
        }
Ejemplo n.º 13
0
 public int BuyFood([FromBody] FoodDTO food)
 {
     try
     {
         var currentUserId = userManager.GetUserId(User);
         var checkId       = new FoodcourtCheck()
         {
             FoodcourtCheckProducts = new List <FoodcourtCheckProduct>(),
             PaidPrice = (decimal)food.Price,
             TransactionDateAndTime = DateTime.Now,
             WorkerId = Guid.Parse(currentUserId)
         };
         for (int i = 0; i < food.TicketIds.Count; ++i)
         {
             checkId.FoodcourtCheckProducts.Add(new FoodcourtCheckProduct()
             {
                 FoodcourtCheckId = checkId.Id,
                 FoodAmountId     = food.TicketIds[i].Id,
                 AmountOfProduct  = food.TicketIds[i].Amount
             });
             var oldFoodAmount = foodAmountService.GetById(food.TicketIds[i].Id);
             oldFoodAmount.ProductAmount -= food.TicketIds[i].Amount;
             foodAmountService.Update(oldFoodAmount);
         }
         foodcourtCheckService.Add(checkId);
         return(checkId.Id);
     }
     catch
     {
         return(0);
     }
 }
Ejemplo n.º 14
0
        private FoodDTO Create(FoodViewModel viewModel)
        {
            try
            {
                log.Debug(FoodViewModel.FormatFoodViewModel(viewModel));

                FoodDTO food = new FoodDTO();

                // copy values
                viewModel.UpdateDTO(food, null); //RequestContext.Principal.Identity.GetUserId());

                // audit
                food.CreateBy = null; //RequestContext.Principal.Identity.GetUserId();
                food.CreateOn = DateTime.UtcNow;

                // add
                log.Debug("_foodService.AddFood - " + FoodDTO.FormatFoodDTO(food));

                int id = _foodService.AddFood(food);

                food.FoodId = id;

                log.Debug("result: 'success', id: " + id);

                return(food);
            }
            catch (Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }
        }
Ejemplo n.º 15
0
 public bool Equals(FoodDTO other)
 {
     if (other == null)
     {
         return(false);
     }
     return(Id.Equals(other.Id));
 }
Ejemplo n.º 16
0
 public Writer(FoodDTO food, string Idkh)
 {
     InitializeComponent();
     this.food         = food;
     this.idkh         = Idkh;
     lbName.Text       = food.Ten;
     pictureBox1.Image = image.AnhCat(0, 0, 240, 270);
 }
 public FoodItem(FoodDTO food, int num)
 {
     InitializeComponent();
     this.lblFoodName.Text   = food.Ten;
     this.lblFoodNumber.Text = "" + num;
     this.Region             = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, this.Width, this.Height, 20, 20));
     lblFoodNumber.Region    = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, lblFoodNumber.Width, lblFoodNumber.Height, 10, 10));
 }
Ejemplo n.º 18
0
 public void Init()
 {
     // Instantiate the class to test
     this.toTest = new FoodDTO()
     {
         Name = "Tomato",
         Mass = 500,
     };
 }
Ejemplo n.º 19
0
        public int UpdateFood(FoodDTO foodDto)
        {
            var factory = _foodDtoValidatorFactory.Create(false);

            factory.ValidateAndThrow(foodDto);

            using (var context = _dbContextScopeFactory.Create())
            {
                var foodContext = context.DbContexts.Get <FoodContext>();
                var food        = foodContext.Foods.Include(x => x.Measures).SingleOrDefault(q => q.FoodId == foodDto.FoodId);
                if (food == null)
                {
                    throw new ValidationException(string.Empty).CreateError(nameof(food.FoodId),
                                                                            ErrorCode.ENTITY_WAS_NOT_FOUND, ErrorCode.ENTITY_WAS_NOT_FOUND);
                }
                if (foodDto.MeasureDtos.AreDuplicates(p => p.Description))
                {
                    var    list    = foodDto.MeasureDtos.GetDuplicates(p => p.Description);
                    string message = string.Empty;
                    foreach (var item in list)
                    {
                        message += item.Description + "-";
                    }
                    throw new ValidationException(string.Empty).CreateError(nameof(foodDto.MeasureDtos),
                                                                            ErrorCode.NEW_ENTITY_IS_ALREADY_IN_REPOSITORY, ErrorCode.NEW_ENTITY_IS_ALREADY_IN_REPOSITORY);
                }
                var dtoToAddList =
                    foodDto.MeasureDtos.Where(dto => dto.MeasureId == 0 && food.Measures.All(entity => entity.Description != dto.Description)).ToList();
                var dtoToUpdate      = foodDto.MeasureDtos.Where(dto => food.Measures.Any(entity => entity.MeasureId == dto.MeasureId)).ToList();
                var entitiesToRemove =
                    food.Measures.Where(entity => foodDto.MeasureDtos.All(dto => dto.MeasureId != entity.MeasureId)).ToList();

                foreach (var entity in entitiesToRemove)
                {
                    foodContext.Measures.Remove(entity);
                }
                foreach (var dto in dtoToAddList)
                {
                    food.Measures.Add(new Measure
                    {
                        Description = dto.Description,
                        Calories    = dto.Calories,
                        TotalFat    = dto.TotalFat
                    });
                }
                foreach (var dto in dtoToUpdate)
                {
                    var measure = food.Measures.Single(p => p.MeasureId == dto.MeasureId);
                    measure.Description = dto.Description;
                    measure.Calories    = dto.Calories;
                    measure.TotalFat    = dto.TotalFat;
                }
                context.SaveChanges();
                return(foodDto.FoodId);
            }
        }
Ejemplo n.º 20
0
        public void ListOfFoodsIdStringsToFoodListTest_withBadInput()
        {
            //Arrange
            var stringFoodId1       = "1";
            var stringFoodId2       = "2";
            var stringFoodId3       = "      ";
            var stringFoodId4       = "4";
            var listOfFoodIdStrings = new List <string> {
                stringFoodId1, stringFoodId2, stringFoodId3, stringFoodId4
            };

            #region Setup4FoodDto
            var food1 = new FoodDTO
            {
                Description      = "Some Test Description, for FoodDTO1",
                FoodCategoryName = "Mad",
                Id    = 1,
                Name  = "Oats Large Flake",
                Price = 218
            };
            var food2 = new FoodDTO
            {
                Description      = "Some Test Description, for FoodDTO2",
                FoodCategoryName = "Drikkevare",
                Id    = 2,
                Name  = "Oil - Food, Lacquer Spray",
                Price = 202
            };
            var food3 = new FoodDTO
            {
                Description      = "Some Test Description, for FoodDTO2",
                FoodCategoryName = "Mad",
                Id    = 3,
                Name  = "Turkey Leg With Drum And Thigh",
                Price = 179
            };
            var food4 = new FoodDTO
            {
                Description      = "Some Test Description, for FoodDTO2",
                FoodCategoryName = "Drikkevare",
                Id    = 4,
                Name  = "Ecolab - Lime - A - Way 4/4 L",
                Price = 112
            };


            #endregion

            var completeFoodInAList = new List <FoodDTO> {
                food1, food2, food3, food4
            };

            // Act => Assert
            Assert.ThrowsException <FormatException>(() => ConvertStringToFoodLists
                                                     .ListOfFoodsIdStringsToFoodList(listOfFoodIdStrings, completeFoodInAList));
        }
Ejemplo n.º 21
0
        public void TestEqualsReverse()
        {
            var tomato = new FoodDTO()
            {
                Name = "Tomato",
                Mass = 500,
            };

            Assert.AreEqual(tomato, this.toTest);
        }
Ejemplo n.º 22
0
        public void TestEquals()
        {
            var tomato = new FoodDTO()
            {
                Name = "Tomato",
                Mass = 500,
            };

            Assert.AreEqual(this.toTest, tomato);
        }
Ejemplo n.º 23
0
        public void TestNotEqualsOnNameAndMass()
        {
            var tomato = new FoodDTO()
            {
                Name = "Tomatooo",
                Mass = 50,
            };

            Assert.AreNotEqual(this.toTest, tomato);
        }
Ejemplo n.º 24
0
 public void Should_Not_Save_Duplicated_Measure_In_Food(FoodDTO foodDto)
 {
     foodDto.FoodId = 0;
     foodDto.MeasureDtos.ForEach(q =>
     {
         q.Description = "SameDescription";
         q.MeasureId   = 0;
     });
     _foodService.Invoking(p => p.AddFood(foodDto)).ShouldThrow <FluentValidation.ValidationException>().And.GetBaseException().Message.Should().Contain(ErrorCode.DUPLICATED_VALUES);
 }
Ejemplo n.º 25
0
        public static FoodDTO SampleFoodDTO(int id = 1)
        {
            FoodDTO food = new FoodDTO();

            // int
            food.FoodId = id;
            // string
            food.Name = "NameTestValue";
            // double?
            food.Quantity = 1;
            // int?
            food.FoodTemplateId = 1;
            // string
            food.SpecificObservations = "SpecificObservationsTestValue";
            // string
            food.Location = "LocationTestValue";
            // int?
            food.Progress = 1;
            // bool
            food.Expired = false;
            // bool
            food.Liquid = false;
            // int?
            food.Rating = 1;
            // string
            food.FeedbackFromBeneficiary = "FeedbackFromBeneficiaryTestValue";
            // int?
            food.DeliveredBy = 1;
            // int?
            food.DeliveredTo = 1;
            // System.DateTime?
            food.OrderDateTime = new System.DateTime();
            // System.DateTime?
            food.CookedDateTime = new System.DateTime();
            // System.DateTime?
            food.PickupDateTime = new System.DateTime();
            // System.DateTime?
            food.StorageDateTime = new System.DateTime();
            // System.DateTime?
            food.DeliveryDateTime = new System.DateTime();
            // bool
            food.Active = false;
            // bool
            food.IsDeleted = false;
            // int?
            food.CreateBy = 1;
            // System.DateTime?
            food.CreateOn = new System.DateTime();
            // int?
            food.UpdateBy = 1;
            // System.DateTime?
            food.UpdateOn = new System.DateTime();

            return(food);
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string  id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            FoodDTO p  = BLL.MONAN.Ins.getMONAN(id);

            txtBoxName.Text      = p.Ten;
            txtBoxUnitPrice.Text = p.Dongia.ToString();
            txtBoxKind.Text      = p.Loai;
            txtBoxNote.Text      = p.Ghichu;
            pictureBox1.Image    = BLL.MONAN.Ins.ByteToImg(p.Hinhanh);
        }
Ejemplo n.º 27
0
        public void TestGetHashCode()
        {
            var tomato = new FoodDTO()
            {
                Name = "Tomato",
                Mass = 500,
            };
            int expected = tomato.GetHashCode();
            int actual   = this.toTest.GetHashCode();

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 28
0
 public SuaMon(string id)
 {
     InitializeComponent();
     food          = MONAN.Ins.getMONAN(id);
     PathImg       = "";
     ImgStrDefault = food.Hinhanh;
     // DataUI
     txtBoxName.Text      = food.Ten;
     txtBoxKind.Text      = food.Loai;
     txtBoxNote.Text      = food.Ghichu;
     txtBoxUnitPrice.Text = food.Dongia;
     pictureBox1.Image    = MONAN.Ins.ByteToImg(food.Hinhanh);
 }
Ejemplo n.º 29
0
        public List <FoodDTO> GetFoodByCategoryID(int id)
        {
            List <FoodDTO> listFood = new List <FoodDTO>();
            string         SQL      = "Select * From Food Where IDCategory = " + id + " And StatusFood = 1";
            DataTable      data     = DBUtilities.Instance.ExecuteQuery(SQL);

            foreach (DataRow item in data.Rows)
            {
                FoodDTO food = new FoodDTO(item);
                listFood.Add(food);
            }
            return(listFood);
        }
Ejemplo n.º 30
0
        //POST
        public static Food Convert(FoodDTO obj)
        {
            var fc = new FoodCategoryDTO(obj.FoodCategoryName);

            return(new Food
            {
                Id = obj.Id,
                Name = obj.Name,
                Description = obj.Description
                              //FoodCategory = Convert(fc), //TODO need to be check if it is needed ?
                              //Price = Convert(new PriceDTO( obj.Price)) //TODO is this needed ?
            });
        }
Ejemplo n.º 31
0
        private FoodDTO helper(string name, string description, string calories, string sugar, string fat, string sats, string salt)
        {
            FoodDTO dto = new FoodDTO();

            dto.Name = name;
            dto.Description = description;
            dto.Calories = calories;
            dto.Sugar = sugar;
            dto.Fat = fat;
            dto.Saturates = sats;
            dto.Salt = salt;

            return dto;
        }