Exemplo n.º 1
0
        public List <JsonRecipe> GetAllFoodFromOneTypeUsingName(string foodName)
        {
            List <JsonRecipe> listOfJsonRecipes = new List <JsonRecipe>();
            var listOfRecipes = FoodDb.Recipes.Where(n => n.Foodtypes.FoodName.ToUpper() == foodName.ToUpper()).ToList();

            foreach (var item in listOfRecipes)
            {
                JsonRecipe oneRecipe = GetOneJsonRecipe(item);
                listOfJsonRecipes.Add(oneRecipe);
            }
            return(listOfJsonRecipes);
        }
Exemplo n.º 2
0
        public List <JsonRecipe> GetAllFoodFromOneType(int FoodTypeId)
        {
            List <JsonRecipe> listOfJsonRecipes = new List <JsonRecipe>();
            var listOfRecipes = FoodDb.Recipes.Where(n => n.FoodTypeId == FoodTypeId).ToList();

            foreach (var item in listOfRecipes)
            {
                JsonRecipe oneRecipe = GetOneJsonRecipe(item);
                listOfJsonRecipes.Add(oneRecipe);
            }
            return(listOfJsonRecipes);
        }
Exemplo n.º 3
0
        public JsonRecipe GetOneJsonRecipeUsingName(Recipe recipe)
        {
            JsonRecipe jsonrecipe = new JsonRecipe
            {
                Id              = recipe.Id,
                Name            = recipe.Name,
                FoodTemperature = recipe.FoodTemperature,
                OvenTemperature = recipe.OvenTemperature,
                Instruction     = recipe.Instruction,
                FoodType        = GetOneFoodType(recipe.FoodTypeId)
            };

            return(jsonrecipe);
        }
Exemplo n.º 4
0
        public JsonRecipe GetRecipe(string ingredients)
        {
            // create url by passing in parameters
            string url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?";

            string param_fillIngredients = "false";
            string param_ingredients     = ingredients;
            string param_limitLicense    = "false";
            string param_number          = "1";
            string param_ranking         = "1";

            // Request query string.
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["fillIngredients"] = param_fillIngredients;
            queryString["ingredients"]     = ingredients;
            queryString["limitLicense"]    = param_limitLicense;
            queryString["number"]          = param_number;
            queryString["ranking"]         = param_ranking;
            var uri = url + queryString;

            // "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1"
            // These code snippets use an open-source library.
            HttpResponse <MemoryStream> responseAPI = Unirest.get(uri)
                                                      .header("X-Mashape-Key", APIKeys.Mashape_Key_Kevin)
                                                      .header("Accept", "application/json")
                                                      .asJson <MemoryStream>();

            // System.IO.MemoryStream encoding to string
            StreamReader reader = new StreamReader(responseAPI.Body);
            string       json   = reader.ReadToEnd();

            // Remove extra brackets on JSON string
            // Unsure if API is returning extra brackets or if StreamReader is adding
            json = json.TrimStart('[');
            json = json.TrimEnd(']');

            // Deserialize json string into an object instance
            JsonRecipe recipeResult = new JsonRecipe();

            JsonConvert.PopulateObject(json, recipeResult);

            return(recipeResult);
        }
Exemplo n.º 5
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            StateClient stateClient = activity.GetStateClient();
            BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // holds response to displayto user
                string answer = "I'm sorry. I didn't understand that. Try: \"What can we cook for dinner?\" or  \"What ingredients are we missing?\"";

                Rootobject luisObj = await LUISClient.ParseUserInput(activity.Text);

                if (luisObj.intents.Length > 0)
                {
                    switch (luisObj.intents[0].intent) // assumption: first intent is highest score
                    {
                    case "":
                        answer = "I'm sorry. I didn't understand that. Try: \"What can we cook for dinner?\" or  \"What ingredients are we missing?\"";
                        break;

                    case "Greeting":
                        answer = "Hello! Feeling hungry and adventurous? Try: \"What can we cook for dinner?\" or  \"I'm hungry!\"";
                        break;

                    case "FindRecipe":

                        answer = "Could you please provide me with a list of ingredeints you have or wish to use?";
                        break;

                    case "PassIngredients":
                        // take in ingredients list and format correctly to pass into API url
                        activity.Text.Remove(0, 6);             // remove "I have "
                        activity.Text.Replace(",", "%2C");      // replace all commas with '%2C'
                        activity.Text.Replace(" ", "");         // remove all spaces if there any
                        var argIngredients = activity.Text;

                        var caller = new CallAPI();

                        if (!caller.isLimitHit())
                        {
                            // Initialize recipeResult to hold json info
                            // Call first API to obtain recipe from ingredients
                            var recipeResult = new JsonRecipe();
                            recipeResult = caller.GetRecipe(argIngredients);


                            // Initialize recipeResult to hold json info
                            // Call second API to obtain recipe link from recipeId
                            var recipeLink = new JsonLink();
                            recipeLink = caller.GetLink(recipeResult.id.ToString());


                            // reply back to user with the recipe options
                            Activity replyMessage        = activity;
                            Activity replyToConversation = replyMessage.CreateReply("May I interest you in..");
                            replyToConversation.Recipient   = replyMessage.From;
                            replyToConversation.Type        = "message";
                            replyToConversation.Attachments = new List <Attachment>();
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: recipeResult.image));
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        plButton    = new CardAction()
                            {
                                Value = recipeLink.sourceUrl,
                                Type  = "openUrl",
                                Title = "Let's Get Cooking!"
                            };
                            cardButtons.Add(plButton);
                            HeroCard plCard = new HeroCard()
                            {
                                Title    = recipeResult.title,
                                Subtitle = "Recommended by " + recipeResult.likes.ToString() + " others!",
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            var replyCard = await connector.Conversations.SendToConversationAsync(replyToConversation);

                            //GetIngredients
                            var dict = new SortedDictionary <string, string>();
                            foreach (var item in recipeLink.extendedIngredients)
                            {
                                dict.Add(item.name, item.aisle);
                            }

                            ShoppingList = "Shopping List: \n";
                            foreach (KeyValuePair <string, string> item in dict.OrderBy(key => key.Value))
                            {
                                ShoppingList += String.Format("{0} ({1}).\n", item.Key, item.Value);
                            }

                            // Store the shoppingList string in the current client state
                            // Allows the string to be accessed in preceeding reply
                            userData.SetProperty <string>("ShoppingList", ShoppingList);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        answer = "It looks like you may be missing some ingredients! Try: \"Send me a grocery list!\"";
                        break;

                    case "GetIngredients":
                        // Retrieve ShoppingList from state
                        answer = userData.GetProperty <string>("ShoppingList");
                        break;
                    }
                }
                else
                {
                    //run out of calls.. try again tomorrow... order out?..pizza #
                    answer = "Sorry! Kitchen is closed.. Time to order out! (425) 453-7200 [Domino's Pizza Bellevue Square]";
                }

                // Return response back to the user
                Activity reply = activity.CreateReply(answer);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Exemplo n.º 6
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            StateClient stateClient = activity.GetStateClient();
            BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // holds response to displayto user
                string answer = "I'm sorry. I didn't understand that. Try: \"What can we cook for dinner?\" or  \"What ingredients are we missing?\"";

                Rootobject luisObj = await LUISClient.ParseUserInput(activity.Text);

                if (luisObj.intents.Length > 0)
                {
                    switch (luisObj.intents[0].intent) // assumption: first intent is highest score
                    {
                    case "":
                        answer = "I'm sorry. I didn't understand that. You can add and remove ingredients from your list or try to find a recipe!";
                        break;

                    case "greeting":
                        answer = "Hello! Feeling hungry and adventurous? You can add and remove ingredients from your list or try to find a recipe!";
                        break;

                    case "addList":
                        // add ingredient(s) to the list
                        // create array to hold entities
                        string[] items = new string[luisObj.entities.Length];

                        // parse the entities and pass in
                        for (int i = 0; i < luisObj.entities.Length; i++)
                        {
                            items[i] = luisObj.entities[i].entity;
                        }

                        // Store the values into a local text file
                        var IngredientsListAdd = new StateList();
                        IngredientsListAdd.AddIngredients(items);

                        answer = "Successfully added ingredients.";
                        break;

                    case "removeList":
                        // remove ingredient(s) to the list
                        // create array to hold entities
                        string[] removeItems = new string[luisObj.entities.Length];

                        // parse the entities and pass in
                        for (int i = 0; i < luisObj.entities.Length; i++)
                        {
                            removeItems[i] = luisObj.entities[i].entity;
                        }

                        // Remove the values from the local text file
                        var IngredientsListRemove = new StateList();
                        IngredientsListRemove.RemoveIngredients(removeItems);

                        answer = "Sucesfully removed ingredients.";
                        break;

                    case "newList":
                        // clear the current list to start new
                        var IngredientsListClear = new StateList();
                        IngredientsListClear.clearIngredients();

                        answer = "Sucesfully clearned the ingredients list. Add more ingredients back!";
                        break;

                    case "displayList":
                        // read current ingredients list
                        var IngredientsListRead = new StateList();
                        var list      = IngredientsListRead.ReadIngredients();
                        var listItems = "";
                        for (int i = 0; i < list.Length; i++)
                        {
                            listItems += (i + 1) + ". " + list[i] + '\n';
                        }

                        answer = "You currently have: \n" + listItems;
                        break;

                    case "findRecipe":
                        // read current ingredients list
                        var IngredientsListAPI = new StateList();
                        var arg = IngredientsListAPI.ReadIngredients();

                        // empty list check
                        if (arg.Length == 0)
                        {
                            answer = "It looks like your ingredients list is empty. Try adding some ingredients then searching for a recipe!";
                            break;
                        }

                        var API_arg = "I have";
                        for (int i = 0; i < arg.Length; i++)
                        {
                            if ((i + 1) == arg.Length)
                            {
                                // last item in array
                                API_arg += " " + arg[i];
                            }
                            else
                            {
                                API_arg += " " + arg[i] + ",";
                            }
                        }

                        var caller = new CallAPI();

                        if (!caller.isLimitHit())
                        {
                            // Initialize recipeResult to hold json info
                            // Call first API to obtain recipe from ingredients
                            var recipeResult = new JsonRecipe();
                            recipeResult = caller.GetRecipe(API_arg);


                            // Initialize recipeResult to hold json info
                            // Call second API to obtain recipe link from recipeId
                            var recipeLink = new JsonLink();
                            recipeLink = caller.GetLink(recipeResult.id.ToString());


                            // reply back to user with the recipe options
                            Activity replyMessage        = activity;
                            Activity replyToConversation = replyMessage.CreateReply("May I interest you in..");
                            replyToConversation.Recipient   = replyMessage.From;
                            replyToConversation.Type        = "message";
                            replyToConversation.Attachments = new List <Attachment>();
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: recipeResult.image));
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        plButton    = new CardAction()
                            {
                                Value = recipeLink.sourceUrl,
                                Type  = "openUrl",
                                Title = "Let's Get Cooking!"
                            };
                            cardButtons.Add(plButton);
                            HeroCard plCard = new HeroCard()
                            {
                                Title    = recipeResult.title,
                                Subtitle = "Recommended by " + recipeResult.likes.ToString() + " others!",
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            var replyCard = await connector.Conversations.SendToConversationAsync(replyToConversation);

                            // Load our current ingredients list we we can cross check and mark what we already have.
                            var IngredientsListGrocery = new StateList();
                            var inventoryList          = IngredientsListGrocery.ReadIngredients();

                            // GetIngredients - complete ingredients from the API response
                            // Load the list into a sorted dictionary with the aisle for user's convenience
                            // Before we load into the dictionary, cross-check to see if we already have the item
                            int counter = 0;
                            var dict    = new SortedDictionary <string, string>();
                            foreach (var item in recipeLink.extendedIngredients)
                            {
                                for (int searchIndex = 0; searchIndex < inventoryList.Length; searchIndex++)
                                {
                                    if (inventoryList[searchIndex] == item.name)
                                    {
                                        item.aisle = "At Home!";
                                    }
                                }
                                dict.Add(item.name, item.aisle);
                                counter++;
                            }

                            // create two arrays, keys = ingredeints, value = aisle.
                            var keyArray   = new string[counter];
                            var valueArray = new string[counter];
                            int index      = 0;
                            foreach (KeyValuePair <string, string> item in dict.OrderBy(key => key.Value))
                            {
                                keyArray[index]   = item.Key;
                                valueArray[index] = item.Value;
                                index++;
                            }

                            userData.SetProperty <string[]>("foodList", keyArray);
                            userData.SetProperty <string[]>("aisleList", valueArray);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        answer = "It looks like you may be missing some ingredients! Try: \"Send me a grocery list!\"";
                        break;

                    case "getShoppingList":
                        // Retrieve ShoppingList from state
                        var foodList  = userData.GetProperty <string[]>("foodList");
                        var aisleList = userData.GetProperty <string[]>("aisleList");
                        var toBuy     = "";

                        // print the cross-checked grocery list for the user
                        for (int i = 0; i < foodList.Length; i++)
                        {
                            toBuy += (i + 1) + ". " + foodList[i] + " (" + aisleList[i] + ")" + '\n';
                        }
                        answer = "Shopping List: \n" + toBuy;
                        break;
                    }
                }
                else
                {
                    //run out of calls.. try again tomorrow... order out?..pizza #
                    answer = "Sorry! Kitchen is closed.. Time to order out! (425) 453-7200 [Domino's Pizza Bellevue Square]";
                }

                // Return response back to the user
                Activity reply = activity.CreateReply(answer);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }