public async Task <IActionResult> Profile()
        {
            Userinfo theUser = new Userinfo();

            try
            {
                string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);//gets userID, don't know a better way.  If you want to find a better way, you can replace this.
                var    users  = from u in _context.Userinfo
                                select u;
                users = users.Where(u => u.Id.Contains(userID));

                if (users.Count() == 0)
                {
                    return(RedirectToAction(nameof(Create)));
                }

                foreach (var user in users)
                {
                    theUser = user;
                }
            }
            catch (Exception ex)
            {
                return(NotFound());
            }

            theUser.Lastloggedin = DateTime.Now;

            try
            {
                _context.Update(theUser);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserinfoExists(theUser.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            int age = 0;

            age = DateTime.Now.Year - theUser.Birthday.Year;
            if (DateTime.Now.DayOfYear < theUser.Birthday.DayOfYear)
            {
                age = age - 1;
            }

            ViewBag.Age      = age;
            ViewBag.Birthday = theUser.Birthday.ToString("MM/dd/yyyy");

            return(View(theUser));
        }
Example #2
0
        public async Task <IActionResult> Create([Bind("Id,Name,Calories,DateEntered,UserId")] Foodinfo foodinfo)
        {
            //makes sure its not null
            if (foodinfo.Name != null)
            {
                //get calories...

                //change spaces to %20
                if (foodinfo.Name.Replace(" ", "%20").Length != 0)
                {
                    foodinfo.Name = foodinfo.Name.Replace(" ", "%20");
                    //call api
                    string url = "https://api.nal.usda.gov/fdc/v1/foods/search?api_key=4yzPQJ6HCWvpCWm6KGaZr1QdIl3UkLhzdXs7os8o&query=" + foodinfo.Name;
                    //change spaces back :P
                    foodinfo.Name = foodinfo.Name.Replace("%20", " ");
                    HttpClient client   = new HttpClient();
                    string     response = await client.GetStringAsync(url);

                    //use json parser
                    var myJObject = JObject.Parse(response);
                    //check if there was at least one hit
                    int hits = (int)myJObject["totalHits"];
                    //if theres at least one valid hit then proceed
                    if (hits > 0)
                    {
                        //stores all nutrient info for the first food
                        IList <JToken>        results       = myJObject["foods"].ElementAt <JToken>(0)["foodNutrients"].ToList();
                        IList <FoodNutrients> foodNutrients = new List <FoodNutrients>();
                        //loop through all Jtokens and map them to a class
                        foreach (JToken result in results)
                        {
                            FoodNutrients foodNutrient = result.ToObject <FoodNutrients>();
                            foodNutrients.Add(foodNutrient);
                        }
                        //loop through list of nutrients to get energy
                        foreach (FoodNutrients nutrient in foodNutrients)
                        {
                            if (nutrient.nutrientName.Equals("Energy"))
                            {
                                //finally set calories to the energy value... YAY!
                                foodinfo.Calories = (int)nutrient.value;
                            }
                        }
                        //set date
                        foodinfo.DateEntered = DateTime.Now;

                        //set user id
                        string userID = User.FindFirstValue(ClaimTypes.NameIdentifier); // I tottally just stole grey's way, cause I don't know a better way....
                        foodinfo.UserId = userID;

                        if (ModelState.IsValid)
                        {
                            _context.Add(foodinfo);
                            await _context.SaveChangesAsync();

                            return(RedirectToAction(nameof(Index)));
                        }
                        ViewData["UserId"] = new SelectList(_context.AspNetUsers, "Id", "Id", foodinfo.UserId);
                    }
                }
            }
            return(View(foodinfo));
        }