Exemplo n.º 1
0
        public ActionResult Create(Meal meal, FormCollection formCollection)
        {
            Dictionary<int, string> NutrientValues = formCollection.AllKeys
                .Where(k => System.Text.RegularExpressions.Regex.IsMatch(k, @"^[0-9]+$"))
                .ToDictionary(k => Convert.ToInt32(k), k => formCollection[k]);

            decimal amount;

            foreach (var nutrient in db.Nutrients)
            {
                if (NutrientValues.ContainsKey(nutrient.NutrientID))
                {
                    // Only add the Nutrient if it has a valid, non zero, value
                    try
                    {
                        amount = Convert.ToDecimal(NutrientValues[nutrient.NutrientID]) * nutrient.PercentageMultiplier;
                    }
                    catch (FormatException)
                    {
                        amount = 0;
                    }
                    catch (OverflowException)
                    {
                        amount = 0;
                    }

                    if (amount != 0)
                    {
                        meal.NutrientAmounts += nutrient.NutrientID + ":" + string.Format("{0:0.##}", amount) + "|";
                    }
                }
            }

            if (meal.NutrientAmounts != null)
            {
                meal.NutrientAmounts = meal.NutrientAmounts.Remove(meal.NutrientAmounts.Length - 1, 1);
            }

            if (ModelState.IsValid)
            {
                db.Meals.Add(meal);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.UserID = new SelectList(db.Users, "UserID", "FirstName", meal.UserID);
            return View(meal);
        }
        public ActionResult Create(DailyDetail dailyDetail, FormCollection formCollection)
        {
            decimal amount, totalAmount;
            dailyDetail.NutrientAmountsDict = new Dictionary<int, decimal>();

            User user = db.Users.Find(1);

            // Create a dictionary from the form fields for each nutrient present
            Dictionary<int, string> NutrientValues = formCollection.AllKeys
                .Where(k => System.Text.RegularExpressions.Regex.IsMatch(k, @"^[0-9]+$"))
                .ToDictionary(k => Convert.ToInt32(k), k => formCollection[k]);

            var servings = dailyDetail.Servings;
            var saveMeal = formCollection.Get("SaveMeal");

            // Get the Totals for the day if it already exists, if not, create a new Total
            DailyTotal dailyTotal = new DailyTotal();
            Meal meal = new Meal();
            meal.NutrientAmountsDict = new Dictionary<int, decimal>();

            // ************************
            var results = db.DailyTotals.Where(s => s.Day == dailyDetail.Day).Where(s => s.UserID == 1).Single();
            if (results != null) {
                dailyTotal = results;
                dailyTotal.NutrientAmountsDict = new Dictionary<int, decimal>();
                dailyTotal.NutrientAmountsDict = gl.DictionaryUnSerializer(dailyTotal.NutrientAmounts);
                dailyTotal.Calories += dailyDetail.Calories;
                dailyTotal.CaloriesFromFat += dailyDetail.CaloriesFromFat;
                dailyTotal.MealCount++;
            }
            else
            {
                dailyTotal = new DailyTotal();
                dailyTotal.Day = dailyDetail.Day;
                dailyTotal.Calories = dailyDetail.Calories * dailyDetail.Servings;
                dailyTotal.CaloriesFromFat = dailyDetail.CaloriesFromFat * dailyDetail.Servings;
                dailyTotal.MealCount = 1;
                dailyTotal.NutrientAmountsDict = new Dictionary<int, decimal>();
                dailyTotal.UserID = user.UserID;
            }

            // Look through all the nutrients to build a list
            foreach (var nutrient in db.Nutrients)
            {
                if (NutrientValues.ContainsKey(nutrient.NutrientID))
                {
                    // Only add the Nutrient if it has a valid, non zero, value
                    try { amount = Convert.ToDecimal(NutrientValues[nutrient.NutrientID]) * nutrient.PercentageMultiplier; }
                    catch (FormatException) { amount = 0; }
                    catch (OverflowException) { amount = 0; }

                    if (amount != 0)
                    {
                        // If a value for the nutrient already exists in the Day's Totals, add it. else set it equal to the amount
                        if (dailyTotal.NutrientAmountsDict.ContainsKey(nutrient.NutrientID)) { totalAmount = dailyTotal.NutrientAmountsDict[nutrient.NutrientID] + amount * dailyDetail.Servings; }
                        else { totalAmount = amount * dailyDetail.Servings; }

                        // Add the amounts to the appropriate dictionaries
                        dailyDetail.NutrientAmountsDict[nutrient.NutrientID] = amount * dailyDetail.Servings;
                        dailyTotal.NutrientAmountsDict[nutrient.NutrientID] = totalAmount;
                        meal.NutrientAmountsDict[nutrient.NutrientID] = amount;
                    }
                }
            }

            // Serialize the Dictionaries to save to the db
            dailyTotal.NutrientAmounts = gl.DictionarySerializer(dailyTotal.NutrientAmountsDict);
            dailyDetail.NutrientAmounts = gl.DictionarySerializer(dailyDetail.NutrientAmountsDict);

            //******************************
            // Save the Meal if the user chose to do so
            if (saveMeal != null) {
                string mealName = formCollection.Get("MealName");
                if (mealName == "") { mealName = "Temp Meal Name"; }

                meal.NutrientAmounts = gl.DictionarySerializer(meal.NutrientAmountsDict);
                meal.Calories = dailyDetail.Calories;
                meal.CaloriesFromFat = dailyDetail.CaloriesFromFat;
                meal.Name = mealName;
                meal.UserID = user.UserID;
                db.NutrientAmounts.Add(meal);
            }

            // Multiply the Calories by the Serving Size
            dailyDetail.Calories *= dailyDetail.Servings;
            dailyDetail.CaloriesFromFat *= dailyDetail.Servings;

            // Commit the changes
            if (ModelState.IsValid)
            {
                db.NutrientAmounts.Add(dailyDetail);
                if (dailyTotal.MealCount == 1) { db.NutrientAmounts.Add(dailyTotal); }
                else { db.Entry(dailyTotal).State = EntityState.Modified; }
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }

            ViewBag.UserID = new SelectList(db.Users, "UserID", "FirstName", dailyDetail.UserID);
            return RedirectToAction("Index", "Home");
        }