示例#1
0
        public async Task <RecipeSearch> Get(string searchQuery, int?numberOfRecords, int?offset)
        {
            var searchResult = new RecipeSearch();

            var key = config["ExternalServices:SpoonacularApiKey"];
            var url = $@"https://api.spoonacular.com/recipes/complexSearch?apiKey={key}&query={searchQuery}&number={numberOfRecords}&offset={offset}";

            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var client  = clientFactory.CreateClient();

            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                searchResult = await response.Content.ReadFromJsonAsync <RecipeSearch>();

                return(searchResult);
            }
            else if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new Exception("Connection to external api failed.");
            }
            else if (response.StatusCode == HttpStatusCode.PaymentRequired)
            {
                throw new Exception("Exceeded amount of daily requests to the external API. Please try again later.");
            }
            else
            {
                throw new Exception("Something Went wrong.");
            }
        }
        protected void BulletedListSearchResults_Click(object sender, BulletedListEventArgs e)
        {
            List <RecipeSearch> recipeSearches = (List <RecipeSearch>)Session["recipeSearches"];
            RecipeSearch        selectedRecipe = recipeSearches[e.Index];

            Response.Redirect(@"~\RecipeView.aspx?selectedRecipeId=" + selectedRecipe.IdRecipe.ToString());
        }
示例#3
0
        public ActionResult SearchRecipe()
        {
            //get call to search page
            RecipeSearch search = new RecipeSearch();

            search.SearchResults = new List <RecipeItemView>();
            return(View(search));
        }
示例#4
0
        public List <Recipe> searchRecipes(RecipeSearch search)
        {
            List <Recipe> searchResults = new List <Recipe>();

            bool bHasTypedText = !string.IsNullOrEmpty(search.TypedText);
            bool bHasUserID    = !search.SearchByUserID.Equals(0);

            string query = "SELECT * FROM [Recipe]";

            if (bHasTypedText)
            {
                query += " WHERE [recipeName] LIKE %@name%";
            }
            //if we have typed text it'll be an "an". if not we're only comparing against user id
            if (bHasUserID && bHasTypedText)
            {
                query += " AND [userId] = @id";
            }
            else if (bHasUserID && !bHasTypedText)
            {
                query += " WHERE [userId] = @id";
            }
            using (SqlConnection conn = new SqlConnection(DB_URL))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(query, conn);
                if (bHasTypedText)
                {
                    cmd.Parameters.AddWithValue("@name", search.TypedText);
                }
                if (bHasUserID)
                {
                    cmd.Parameters.AddWithValue("@id", search.SearchByUserID);
                }
                SqlDataReader results = cmd.ExecuteReader();
                while (results.Read())
                {
                    Recipe r = new Recipe();
                    r.RecipeID   = getValueOrDefault <int>(0, results);
                    r.RecipeName = getValueOrDefault <string>(2, results);
                    r.UserID     = getValueOrDefault <int>(1, results);
                    string stepJSON = getValueOrDefault <string>(3, results);
                    r.Steps = JsonConvert.DeserializeObject <List <Step> >(stepJSON);
                    r.Icon  = getValueOrDefault <string>(4, results);
                    r.Tags  = getValueOrDefault <string>(5, results);
                    string ingredientJSON = getValueOrDefault <string>(6, results);
                    r.Ingredients       = JsonConvert.DeserializeObject <List <Ingredient> >(ingredientJSON);
                    r.CreatedOnDateTime = getValueOrDefault <DateTime>(7, results);

                    searchResults.Add(r);
                }
            }
            return(searchResults);
        }
        public List <Recipe> Get([FromHeader] string auth, [FromRoute] long id)
        {
            string user;

            if ((user = JwtBuilder.UserJwtToken(auth).Result) == null || !UserStore.Exists(user).Result)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(null);
            }

            HttpContext.Response.Headers.Add("auth", auth);
            return(RecipeSearch.SearchRecipe(API_KEY, new List <long> {
                id
            }));
        }
示例#6
0
        public ActionResult SearchRecipe(RecipeSearch search)
        {
            //run the search function and send back the results
            List <Recipe>         searchResults    = oFactory.recipeEndpoint.searchRecipes(search);
            List <RecipeItemView> viewModelResults = new List <RecipeItemView>();

            foreach (Recipe result in searchResults)
            {
                RecipeItemView riv = new RecipeItemView();
                riv.Recipe        = result;
                riv.CreatedByUser = oFactory.userEndpoint.getUserById(result.UserID);
                riv.Reviews       = oFactory.reviewEndpoint.getReviewsForRecipe(result.RecipeID);
                viewModelResults.Add(riv);
            }
            search.SearchResults = viewModelResults;
            return(View(search));
        }
        private void FillDatabaseObjects()
        {
            WebsiteContext   C  = GetInMemoryDBWithSeeder();
            SearchController SC = new SearchController(C);

            DatabaseObject Employee = new EmployeeSearch(C);
            DatabaseObject Product  = new ProductSearch(C);
            DatabaseObject Recipe   = new RecipeSearch(C);
            DatabaseObject News     = new NewsSearch(C);

            Employee.SetObject(C.Employee_Profiles.ToList().ElementAt(0));
            Product.SetObject(C.Products.ToList().ElementAt(0));
            Recipe.SetObject(C.Recipes.ToList().ElementAt(0));
            News.SetObject(C.News_Items.ToList().ElementAt(0));

            EmployeeTest = Employee;
            ProductTest  = Product;
            RecipeTest   = Recipe;
            NewsTest     = News;
        }
        public async Task <RecipeSearch> Get(string searchQuery, int?numberOfRecords, int?offsetRecords)
        {
            var search = new RecipeSearch();

            using (StreamReader r = new StreamReader("search.json"))
            {
                //Load list of recipes
                string json = await r.ReadToEndAsync();

                r.Close();

                var result = JsonConvert.DeserializeObject <RecipeSearch>(json);
                search = result;
            }


            var searchResults = search.results
                                .Where(t => t.title.ToLower().Contains(searchQuery.Trim().ToLower()));

            //Create a new result object array from the search query string
            var filteredResults = searchResults
                                  .Skip(Convert.ToInt32(offsetRecords))
                                  .Take(Convert.ToInt32(numberOfRecords))
                                  .ToArray();

            //Assign values needed for a new return object
            var filteredResultsCount  = searchResults.Count();
            var filteredResultsOffset = Convert.ToInt32(offsetRecords);
            var filteredResultsNumber = Convert.ToInt32(numberOfRecords);

            //Build the new object to return back
            var filteredSearch = new RecipeSearch()
            {
                results      = filteredResults,
                totalResults = filteredResultsCount,
                number       = filteredResultsNumber,
                offset       = filteredResultsOffset
            };

            return(filteredSearch);
        }
        public async Task <List <MinimalRecipe> > Search([FromHeader] string auth, [FromForm] string keys, [FromForm] string inventory)
        {
            string user;

            if ((user = JwtBuilder.UserJwtToken(auth).Result) == null || !UserStore.Exists(user).Result)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(null);
            }

            List <MinimalRecipe> list;

            HttpContext.Response.Headers.Add("auth", auth);
            if (inventory != null)
            {
                var inv = InventoryStore.Get(inventory, user).Result;
                if (inv == null)
                {
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    return(null);
                }

                var r = new List <Product>(inv._products);
                list = RecipeSearch.SearchMinimalRecipe(API_KEY, 10, r);
            }

            else
            {
                list = RecipeSearch.SearchMinimalRecipe(API_KEY, 10, keys);
            }

            foreach (var v in list)
            {
                await RecipeStore.Add(v);
            }

            return(list);
        }