Ejemplo n.º 1
0
        private async void UndoButton_Clicked(object sender, EventArgs e)
        {
            var data = Application.Current.Properties;
            var x    = foodObj.ClassId;

            if (x.Contains("Meal"))
            {
                x = x.Replace("Meal", "");
                data["removedMeals"] += x + ",";

                var       q           = data[x + "Meal"].ToString();
                MealModel foodClicked = JsonConvert.DeserializeObject <MealModel>(q);
                foreach (var fod in foodClicked.foodClassIds)
                {
                    var       qq           = data[fod + "food"].ToString();
                    FoodModel foodClicked2 = JsonConvert.DeserializeObject <FoodModel>(qq);
                    foodClicked2.isPartOfMeal = false;
                    qq = JsonConvert.SerializeObject(foodClicked2);
                    data[fod + "food"] = qq;
                }
                foodClicked.foodClassIds.Clear();

                data.Remove(x + "Meal");
                await Application.Current.SavePropertiesAsync();
            }
            else
            {
                //nothing
            }
            MealView.Invoker.UpdateAllButtons();
            CloseAllPopup();
        }
Ejemplo n.º 2
0
        private async void FoodEntry_Unfocused(object sender, FocusEventArgs e) //change name
        {
            if (FoodEntry.Text != "" && FoodEntry.Text != null)
            {
                FoodName.Text = FoodEntry.Text;
                var x = foodObj.ClassId;
                if (x.Contains("Meal"))
                {
                    x = x.Replace("Meal", "");
                    var       data        = Application.Current.Properties;
                    var       q           = data[x + "Meal"].ToString();
                    MealModel foodClicked = JsonConvert.DeserializeObject <MealModel>(q);
                    foodClicked.MealName = FoodName.Text;
                    q = JsonConvert.SerializeObject(foodClicked);
                    data[x + "Meal"] = q;
                    await Application.Current.SavePropertiesAsync();
                }
                else
                {
                    var       data        = Application.Current.Properties;
                    var       q           = data[x + "food"].ToString();
                    FoodModel foodClicked = JsonConvert.DeserializeObject <FoodModel>(q);
                    foodClicked.Name = FoodName.Text;
                    q = JsonConvert.SerializeObject(foodClicked);
                    data[x + "food"] = q;
                    await Application.Current.SavePropertiesAsync();
                }

                MealView.Invoker.UpdateAllButtons();
            }


            FoodName.IsVisible  = true;
            FoodEntry.IsVisible = false;
        }
Ejemplo n.º 3
0
 public int AddMeal(int userId, MealModel meal)
 {
     using (var context = GetContext())
     {
         var dbMeal = context.Meals.SingleOrDefault(m => m.UserId == userId && m.MealId == meal.MealId);
         if (dbMeal != null)
         {
             throw new BadArgumentException("Meal does not exists.");
         }
         var today  = DateTime.Now;
         var mealId = 1;
         if (context.Meals.Any(m => m.UserId == userId))
         {
             mealId = context.Meals.Where(m => m.UserId == userId).Max(m => m.MealId + 1);
         }
         dbMeal = new Meal()
         {
             UserId      = userId,
             MealId      = mealId,
             Date        = meal.Date.Date,
             Time        = meal.Date.TimeOfDay,
             Description = meal.Description,
             Calories    = meal.Calories,
             Created     = today,
             Modified    = today,
         };
         context.Meals.Add(dbMeal);
         context.SaveChanges();
         return(mealId);
     }
 }
Ejemplo n.º 4
0
        public static void SetupMeals(MealModel model)
        {
            using (var site = new SCBWIContext()) {
                site.Information.Add(new Information {
                    Category = Category.Lunch,
                    Title    = model.Meal1,
                    Value    = model.Meal1
                });

                site.Information.Add(new Information
                {
                    Category = Category.Lunch,
                    Title    = model.Meal2,
                    Value    = model.Meal2
                });

                site.Information.Add(new Information
                {
                    Category = Category.Lunch,
                    Title    = model.Meal3,
                    Value    = model.Meal3
                });

                site.SaveChanges();
            }
        }
Ejemplo n.º 5
0
        public List <MealModel> DisplayEntries(string userName)
        {
            List <MealModel> meals = new List <MealModel>();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT fdc_id, meal_id, food_name, consumption_date, servings, meal_type, food_calories, total_calories FROM meals WHERE user_name = @userName", conn);
                cmd.Parameters.AddWithValue("@userName", userName);


                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    MealModel meal = new MealModel();
                    meal.FDCID           = Convert.ToInt32(reader["fdc_id"]);
                    meal.MealID          = Convert.ToInt32(reader["meal_id"]);
                    meal.FoodName        = Convert.ToString(reader["food_name"]);
                    meal.ConsumptionDate = Convert.ToDateTime(reader["consumption_date"]);
                    meal.Servings        = Convert.ToDecimal(reader["servings"]);
                    meal.MealType        = Convert.ToString(reader["meal_type"]);
                    meal.FoodCalories    = Convert.ToInt32(reader["food_calories"]);
                    meal.TotalCalories   = Convert.ToInt32(reader["total_calories"]);
                    meals.Add(meal);
                }
            }
            return(meals);
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Update(int id, MealModel model)
        {
            try
            {
                var meal = await _mealsRepository.GetByIdAsync(id);

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

                meal.Name          = model.Name;
                meal.Description   = model.Description;
                meal.PrepEffort    = (MealPrepEffort)model.PrepEffort;
                meal.IsFavorite    = model.IsFavorite;
                meal.IsKidFriendly = model.IsKidFriendly;

                await _mealsRepository.UpdateAsync(meal);

                _logger.LogInformation("Updated meal {id}", id);

                return(Ok(model));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating meal {id}", id);
                return(StatusCode(500));
            }
        }
Ejemplo n.º 7
0
        public RadButton CustomMealCreator(MealModel meal, int row, int col)
        {
            var data = Xamarin.Forms.Application.Current.Properties;

            RadButton custombutton = new RadButton
            {
                Text                 = meal.MealName,
                ClassId              = meal.MealClassId.ToString(),
                VerticalOptions      = LayoutOptions.Center,
                HorizontalOptions    = LayoutOptions.Center,
                MinimumHeightRequest = 50,
                WidthRequest         = 300,
                BackgroundColor      = Color.MediumVioletRed,
                TextColor            = Color.Black,
                BorderColor          = Color.White,
                CornerRadius         = 60,
            };

            buttonlist.Add(custombutton);
            //PROSOXI EXW BALEI NA GINONTAI DISABLE TA MEAL KOUMPIA ME VASEI TO XRWMA
            //PSAKSE REFERENCE TOU buttonslist GIA NA TO DEIS
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            custombutton.Clicked += async(sender, args) => {
                if (combineActive)
                {
                    return;
                }
                if (longpress)
                {
                    return;
                }
                foreach (var clsId in meal.foodClassIds)
                {
                    Xamarin.Forms.Button fakebtn = new Xamarin.Forms.Button();
                    fakebtn.ClassId = clsId.ToString();
                    OnButtonClicked(fakebtn, args);
                }
                var       q           = data[meal.MealClassId.ToString() + "Meal"].ToString();
                MealModel mealClicked = JsonConvert.DeserializeObject <MealModel>(q);
                mealClicked.TimesPressed += 1;
                ShowTimesMealPressed(mealClicked.TimesPressed, (sender as Xamarin.Forms.Button));
                var qq = JsonConvert.SerializeObject(mealClicked);
                data[mealClicked.MealClassId.ToString() + "Meal"] = qq;
                await Xamarin.Forms.Application.Current.SavePropertiesAsync();
            };
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            var stackLayout = new StackLayout
            {
                Children = { custombutton }
            };
            custombutton.Behaviors.Add(new LongPressBehavior());     //LONG PRESS BEHAVIORS
            var yo = custombutton.Behaviors[0] as LongPressBehavior; //LONG PRESS BEHAVIORS
            yo.LongPressed           += OnMealLongPressed;           //LONG PRESS BEHAVIORS
            custombutton.Behaviors[0] = yo;                          //LONG PRESS BEHAVIORS
            Grid.SetRow(stackLayout, row);
            Grid.SetColumn(stackLayout, col);
            ButtonGrid.Children.Add(stackLayout);
            return(custombutton);
        }
Ejemplo n.º 8
0
        public async void DeleteConfirmed()
        {
            var data = Application.Current.Properties;
            var x    = foodObj.ClassId;

            if (x.Contains("Meal"))
            {
                x = x.Replace("Meal", "");
                var       q           = data[x + "Meal"].ToString();
                MealModel foodClicked = JsonConvert.DeserializeObject <MealModel>(q);
                foreach (var fod in foodClicked.foodClassIds)
                {
                    data["removedClassIds"] += fod + ",";
                    data.Remove(fod + "food");
                }
                data["removedMeals"] += x + ",";
                data.Remove(x + "Meal");
            }
            else
            {
                data["removedClassIds"] += x + ",";
                data.Remove(x + "food");
                // (btn.Parent as StackLayout).Children.Clear();
            }
            MealView.Invoker.UpdateAllButtons();
            await Application.Current.SavePropertiesAsync();

            OnCloseButtonTapped(null, null); //close page
        }
        public async Task <int> AddMealInDiet(int dietId, MealModel mealModel)
        {
            HttpResponseMessage responseMessage =
                await client.PostAsync($"{uri}/{dietId}/meals", PrepareObjectForRequest(mealModel));

            return(int.Parse(await responseMessage.Content.ReadAsStringAsync()));
        }
Ejemplo n.º 10
0
        public ActionResult EditMeals(int?i)
        {
            if (Session["UserID"] != null && Session["UserType"].ToString().ToLower() == "chef")
            {
                if (i == null)
                {
                    return(RedirectToAction("Index", "Order"));
                }

                List <DAL.Meal>         meals         = mRepo.GetCurrent();
                List <DAL.OrderProduct> orderProducts = opRepo.GetCurrent();
                MealListModel           mealList      = new MealListModel();

                foreach (DAL.Meal ml in meals)
                {
                    MealModel mealmodel = new MealModel();
                    mealmodel.ID       = ml.ID;
                    mealmodel.Name     = ml.Name;
                    mealmodel.Quantity = 0;
                    foreach (DAL.OrderProduct op in orderProducts)
                    {
                        if (op.OrderID == i && op.MealID == ml.ID)
                        {
                            mealmodel.Quantity = (int)op.Quantity;
                        }
                    }
                    mealList.mm.Add(mealmodel);
                }
                ViewBag.orderID = i;
                return(View(mealList));
            }
            return(RedirectToAction("Login", "Home", new { area = "" }));
        }
Ejemplo n.º 11
0
        public IActionResult AddMeal([FromBody] MealModel meal)
        {
            meal.UserName = User.Identity.Name;
            mealDao.AddMeal(meal);

            return(Ok());
        }
Ejemplo n.º 12
0
        private void addMealBtn_Click(object sender, EventArgs e)
        {
            string mealName  = nameTB.Text;
            int    mealPrice = Int32.Parse(priceTB.Text);

            int salt   = Int32.Parse(saltTB.Text);
            int sweet  = Int32.Parse(sweetTB.Text);
            int sour   = Int32.Parse(sourTB.Text);
            int spicy  = Int32.Parse(spicyTB.Text);
            int bitter = Int32.Parse(bitterTB.Text);

            string _connectionString = "Data Source=" +
                                       Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\OO_PocketGourmet_REAL-UnitTest\MVPDB.sqlite;";
            MealServices mealServices = new MealServices(new MealRepository(_connectionString), new ModelDataAnnotationCheck());
            MealModel    meal         = new MealModel()
            {
                MealName        = mealName,
                MealPrice       = mealPrice,
                MealSaltTaste   = salt,
                MealSweetTaste  = sweet,
                MealSourTaste   = sour,
                MealSpicyTaste  = spicy,
                MealBitterTaste = bitter,
                MealRestaurant  = rID
            };

            mealServices.Add(meal);
            MessageBox.Show("Meal Added");
        }
Ejemplo n.º 13
0
        public ActionResult AddMeal(MealModel model)
        {
            string UserName = (string)Session["UserName"];

            if (ModelState.IsValid)
            {
                int id = mealInformation.AddMeal(model, UserName);
                if (id > 0)
                {
                    ViewBag.Success = "Meal Added";
                    ModelState.Clear();
                }
                else if (id == -1)
                {
                    ViewBag.Success = "Time Is Over";
                }
                else if (id == -3)
                {
                    ViewBag.Success = "You already added meal You can just update it";
                }
                else if (id == -2)
                {
                    ViewBag.Success = "Insufficient Balance!";
                }
            }
            return(View());
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Saves the user to the database.
        /// </summary>
        /// <param name="user"></param>
        public void AddMeal(MealModel meal)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO meals VALUES (@mealId, @foodName, @consumptionDate, @servings, @mealType, @foodCalories, @totalCalories, @userName);", conn);
                    cmd.Parameters.AddWithValue("@mealId", meal.FDCID);
                    cmd.Parameters.AddWithValue("@foodName", meal.FoodName);
                    cmd.Parameters.AddWithValue("@consumptionDate", meal.ConsumptionDate);
                    cmd.Parameters.AddWithValue("@servings", meal.Servings);
                    cmd.Parameters.AddWithValue("@mealType", meal.MealType);
                    cmd.Parameters.AddWithValue("@foodCalories", meal.FoodCalories);
                    cmd.Parameters.AddWithValue("@totalCalories", meal.TotalCalories);
                    cmd.Parameters.AddWithValue("@userName", meal.UserName);

                    cmd.ExecuteNonQuery();

                    return;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 15
0
        private MealItem CreateMealItem(MealModel mm)
        {
            MealItem item = new MealItem(mm, this);

            item.Dock = DockStyle.Top;
            return(item);
        }
Ejemplo n.º 16
0
        public async Task <ActionResult <MealModel> > Create(MealModel model)
        {
            try
            {
                var meal = new Meal
                {
                    Name          = model.Name,
                    Description   = model.Description,
                    PrepEffort    = (MealPrepEffort)model.PrepEffort,
                    IsFavorite    = model.IsFavorite,
                    IsKidFriendly = model.IsKidFriendly
                };

                await _mealsRepository.CreateAsync(meal);

                _logger.LogInformation("Created meal");

                model = _mapper.Map <MealModel>(meal);
                return(CreatedAtAction("GetById", new { id = model.Id }, model));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating meal");
                return(StatusCode(500));
            }
        }
Ejemplo n.º 17
0
        //User adds meal
        public async Task AddMealAsync(UserModel user, MealModel meal)
        {
            if (user.Position == (int)UserPosition.HasNotHome)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Home Not Exist", "User is not member of a home");
                errors.Throw();
            }

            user = await _userRepository.GetByIdAsync(user.Id, true);

            HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true);

            MealModel tmp = await _mealRepository.GetHomeMealByNameAsync(home.Id, meal.Name);

            if (tmp != null)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Meal Already Exist", "This meal has already exist");
                errors.Throw();
            }

            meal.Home = home;

            _mealRepository.Insert(meal);

            foreach (var friend in home.Users)
            {
                FCMModel fcm = new FCMModel(friend.DeviceId, type: "AddMeal");
                fcm.data.Add("Meal", meal);
                await _fcmService.SendFCMAsync(fcm);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="logger"></param>
        /// <param name="meal">食事モデル</param>
        public MealViewModel(ISettings settings, ILogger logger, MealModel meal)
        {
            this._settings = settings;
            this._logger   = logger;
            this.Meal      = meal.AddTo(this.CompositeDisposable);

            // Property
            // 食事ID
            this.MealId = this.Meal.MealId.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(this.CompositeDisposable);
            // レシピリスト
            this.RecipeList = this.Meal.Recipes.ToReadOnlyReactiveCollection(recipe => Creator.CreateRecipeViewModelInstance(settings, logger, recipe)).AddTo(this.CompositeDisposable);
            // 食事タイプ
            this.MealType = this.Meal.MealType.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(this.CompositeDisposable);
            // 食事タイプリスト
            this.MealTypes = this.Meal.MealTypes.ToReadOnlyReactiveCollection().AddTo(this.CompositeDisposable);

            // Command
            // レシピ追加コマンド
            this.AddRecipeCommand.Subscribe(() => {
                using (var vm = new AddRecipeViewModel(this._settings, this._logger, Method.HistorySearch | Method.Download | Method.Original)) {
                    this.Messenger.Raise(new TransitionMessage(vm, "OpenSearchRecipeWindow"));
                    if (vm.IsSelectionCompleted.Value)
                    {
                        this.Meal.AddRecipe(vm.SelectionResult.Value.Recipe);
                    }
                }
            }).AddTo(this.CompositeDisposable);
            // レシピ削除コマンド
            this.RemoveRecipeCommand.Subscribe(rvm => {
                using (var vm = new DialogWindowViewModel(
                           "削除確認",
                           "食事からレシピを削除します。よろしいですか。",
                           DialogWindowViewModel.DialogResult.Yes,
                           DialogWindowViewModel.DialogResult.No
                           )) {
                    this.Messenger.Raise(new TransitionMessage(vm, TransitionMode.Modal, "OpenDialogWindow"));
                    if (vm.Result == DialogWindowViewModel.DialogResult.Yes)
                    {
                        this.Meal.RemoveRecipe(rvm.Recipe);
                    }
                }
            }).AddTo(this.CompositeDisposable);

            // 食事削除コマンド
            this.RemoveMealCommand.Subscribe(() => {
                using (var vm = new DialogWindowViewModel(
                           "削除確認",
                           "食事を削除します。よろしいですか。",
                           DialogWindowViewModel.DialogResult.Yes,
                           DialogWindowViewModel.DialogResult.No
                           )) {
                    this.Messenger.Raise(new TransitionMessage(vm, TransitionMode.Modal, "OpenDialogWindow"));
                    if (vm.Result == DialogWindowViewModel.DialogResult.Yes)
                    {
                        this.Meal.RemoveMeal();
                    }
                }
            }).AddTo(this.CompositeDisposable);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates the name of the file.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>FileName without extension.</returns>
        internal static string CreateFileName(MealModel model)
        {
            var    date     = model.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            string fileName = $"{date}-{model.Restaurant}";

            fileName = HttpUtility.UrlEncode(fileName);
            return(fileName);
        }
 public static MealModel ToModel(this MealPoco poco)
 {
     var model = new MealModel();
     model.Calories = poco.Calories;
     model.DateTime = poco.DateTime;
     model.Text = poco.Text;
     model.Id = poco.Id;
     return model;
 }
Ejemplo n.º 21
0
        public void LogMeal(MealModel mealToBeLogged, long id)
        {
            var user = _users.FirstOrDefault(x => x.Id == id);

            user.MealsConsumed.Add(new Meal
            {
                Id       = mealToBeLogged.Id,
                Name     = mealToBeLogged.Name,
                Products = mealToBeLogged.Products
            });
        }
Ejemplo n.º 22
0
        public ActionResult MealView()
        {
            MealModel model = new MealModel();

            using (SQLContext context = GetSQLContext())
            {
                model.Meals = context.Meals.ToList();
            }

            return(View(model));
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> UpdateMeal([FromBody] MealModel meal)
        {
            string    token = Request.Headers["Authorization"].ToString().Substring("Bearer ".Length).Trim();
            UserModel user  = await _jwtTokenService.GetUserFromTokenStrAsync(token);

            meal.Name = meal.Name.ToLower();

            await _menuService.UpdateMealAsync(user, meal);

            return(Ok());
        }
Ejemplo n.º 24
0
        public ActionResult Meals(MealModel model)
        {
            if (ModelState.IsValid)
            {
                DAL.SetupMeals(model);
                return(RedirectToAction("Tracks"));
            }

            ModelState.AddModelError("", "Your prices were not set correctly. Please try again.");
            return(View(model));
        }
Ejemplo n.º 25
0
        public async void setWindow(string text)
        {
            MealModel mm = await DataProccesor.LoadMeal(text);

            pictureBox1.Load(mm.strMealThumb);

            this.Text = "Recipe - " + mm.strMeal;

            label1.Text = mm.strMeal; //first label in ListBox for title of recipe
            fillListBox(mm);          //calling function that will handle item in the right container
            textBox1.Text = mm.strInstructions;
        }
Ejemplo n.º 26
0
        public MealModel GetByID(int id)
        {
            //throw new NotImplementedException();
            MealModel        mealModel         = new MealModel();
            DataAccessStatus dataAccesStatus   = new DataAccessStatus();
            bool             MatchingMealFound = false;
            string           sql = "SELECT * FROM Meals WHERE MealID = @MealID";

            using (SQLiteConnection sqLiteConnection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    sqLiteConnection.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(sql, sqLiteConnection))
                    {
                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@MealID", id));
                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            MatchingMealFound = reader.HasRows;
                            while (reader.Read())
                            {
                                mealModel.MealID         = Int32.Parse(reader["MealID"].ToString());
                                mealModel.MealName       = reader["MealName"].ToString();
                                mealModel.MealPrice      = Int32.Parse(reader["MealPrice"].ToString());
                                mealModel.MealRestaurant = Int32.Parse(reader["MealRestaurant"].ToString());

                                mealModel.MealSaltTaste   = Int32.Parse(reader["MealSaltTaste"].ToString());
                                mealModel.MealSourTaste   = Int32.Parse(reader["MealSourTaste"].ToString());
                                mealModel.MealSpicyTaste  = Int32.Parse(reader["MealSpicyTaste"].ToString());
                                mealModel.MealSweetTaste  = Int32.Parse(reader["MealSweetTaste"].ToString());
                                mealModel.MealBitterTaste = Int32.Parse(reader["MealBitterTaste"].ToString());
                            }
                        }
                        sqLiteConnection.Close();
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccesStatus.setValues(status: "Error", operationSucceded: false, exceptionMessage: e.Message, customMessage: "Unable to get Meal Model from db", helpLink: e.HelpLink, errorCode: e.ErrorCode, stackTrace: e.StackTrace);
                    throw new DataAccessException(e.Message, e.InnerException, dataAccesStatus);
                }

                if (!MatchingMealFound)
                {
                    dataAccesStatus.setValues(status: "Error", operationSucceded: false, exceptionMessage: "", customMessage: "Unable to find Meal Model in db", helpLink: "", errorCode: 0, stackTrace: "");
                    throw new DataAccessException(dataAccesStatus);
                }
                return(mealModel);
            }
        }
Ejemplo n.º 27
0
        //Update Meal
        public async Task <CreateMealModelResponse> UpdateMeal(MealModel mealModel)
        {
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "dc7fdbb7c51275af932b2669ccb737fe91432018");
            var json    = JsonConvert.SerializeObject(mealModel);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await _client.PutAsync("http://healthlog-deployment.dbmvyepwfm.us-east-1.elasticbeanstalk.com/api/meals/", content);

            var result = await response.Content.ReadAsStringAsync();

            var meal = JsonConvert.DeserializeObject <CreateMealModelResponse>(result);

            return(meal);
        }
        public int AddMeal(MealModel model, string UserName)
        {
            var user    = searchOperation.GetUser(UserName);
            var student = searchOperation.GetStudent(user.UserId);
            var room    = searchOperation.GetRoom((int)student.RoomId);

            using (var context = new HallAutomationSystemEntities())
            {
                var meal = context.Meal.FirstOrDefault(x => x.StudentId == student.StudentId);
                if (meal != null)
                {
                    return(-3);
                }
            }
            TimeSpan now   = DateTime.Now.TimeOfDay;
            TimeSpan start = new TimeSpan(00, 0, 0);
            TimeSpan End   = new TimeSpan(24, 00, 0);

            if (!(now >= start && now <= End))
            {
                return(-1);
            }
            Account account   = searchOperation.GetAccount(student.StudentId);
            int     taka      = searchOperation.GetMealCost();
            int     meal_cost = (model.Dinnar * taka + model.Lunch * taka);

            if (meal_cost > account.Balance)
            {
                return(-2);
            }
            else
            {
                accountInformation.decreamentAccountBalance(student.StudentId, meal_cost);
            }
            using (var context = new HallAutomationSystemEntities())
            {
                Meal meal = new Meal()
                {
                    StudentId   = student.StudentId,
                    RoomNo      = room.RoomNumber,
                    Dinnar      = model.Dinnar,
                    Lunch       = model.Lunch,
                    Time        = DateTime.Now.TimeOfDay,
                    Date        = DateTime.Today,
                    StudentName = student.StudentName
                };
                context.Meal.Add(meal);
                context.SaveChanges();
                return(meal.MealId);
            }
        }
Ejemplo n.º 29
0
        public async Task InsertMealIntoTable(MealModel model)
        {
            var table = await _tableStorage.GetTableReference(_mealsTable);

            var entity = new MealEntity()
            {
                PartitionKey   = Guid.NewGuid().ToString(),
                RowKey         = new Guid().ToString(),
                MealsModelData = model
            };

            var tableOperation = TableOperation.InsertOrMerge(entity);
            await table.ExecuteAsync(tableOperation);
        }
Ejemplo n.º 30
0
        public static IActionResult GetMealById(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "meals/{id}")] HttpRequest req,
            string id,
            [Blob("meals/{id}.json", FileAccess.ReadWrite, Connection = "StorageSend")] string blob,
            ILogger log,
            ExecutionContext context)
        {
            Guid          correlationId = Util.ReadCorrelationId(req.Headers);
            var           methodName    = MethodBase.GetCurrentMethod().Name;
            var           trace         = new Dictionary <string, string>();
            EventId       eventId       = new EventId(correlationId.GetHashCode(), Constants.ButlerCorrelationTraceName);
            IActionResult actionResult  = null;

            MealModel mealModel = null;

            using (log.BeginScope("Method:{methodName} CorrelationId:{CorrelationId} Label:{Label}", methodName, correlationId.ToString(), context.InvocationId.ToString()))
            {
                try
                {
                    trace.Add(Constants.ButlerCorrelationTraceName, correlationId.ToString());
                    trace.Add("id", id);
                    mealModel = JsonConvert.DeserializeObject <MealModel>(blob);

                    log.LogInformation(correlationId, $"'{methodName}' - success", trace);
                    actionResult = new OkObjectResult(mealModel);
                }
                catch (Exception e)
                {
                    trace.Add(string.Format("{0} - {1}", methodName, "rejected"), e.Message);
                    trace.Add(string.Format("{0} - {1} - StackTrace", methodName, "rejected"), e.StackTrace);
                    log.LogInformation(correlationId, $"'{methodName}' - rejected", trace);
                    log.LogError(correlationId, $"'{methodName}' - rejected", trace);

                    ErrorModel errorModel = new ErrorModel()
                    {
                        CorrelationId = correlationId,
                        Details       = e.StackTrace,
                        Message       = e.Message,
                    };
                    actionResult = new BadRequestObjectResult(errorModel);
                }
                finally
                {
                    log.LogTrace(eventId, $"'{methodName}' - finished");
                    log.LogInformation(correlationId, $"'{methodName}' - finished", trace);
                }
            }

            return(actionResult);
        }
Ejemplo n.º 31
0
        public MealItemGuest(MealModel mm, ListMealsGuestForm lmf)
        {
            InitializeComponent();
            mealm       = mm;
            Lmf         = lmf;
            nameL.Text  = mm.MealName;
            priceL.Text = mm.MealPrice.ToString();

            sourL.Text   = mm.MealSourTaste.ToString();
            saltL.Text   = mm.MealSaltTaste.ToString();
            spicyL.Text  = mm.MealSpicyTaste.ToString();
            bitterL.Text = mm.MealBitterTaste.ToString();
            sweetL.Text  = mm.MealSweetTaste.ToString();
        }