Example #1
0
        public void RecipeFinderResults_ShouldCallContextRecipeSearch()
        {
            var testQuery    = new RecipeQuery();
            var recipeFinder = new RecipeFinder(this.Context, testQuery);

            this.Context.RSCalledTimes = 0;

            var search = recipeFinder.Results();

            var query = this.Context.search;

            Assert.AreEqual(1, this.Context.RSCalledTimes);

            CollectionAssert.AreEqual(query.Include, new Guid[0]);
            CollectionAssert.AreEqual(query.Exclude, new Guid[0]);
            Assert.AreEqual(query.Keywords, null);
            Assert.AreEqual(query.Meal, MealFilter.All);
            Assert.AreEqual(query.Photos, PhotoFilter.All);
            Assert.AreEqual(query.Rating, Rating.None);
            Assert.AreEqual(SortOrder.Rating, query.Sort);
            Assert.AreEqual(SortDirection.Descending, query.Direction);

            Assert.AreEqual(query.Time, new TimeFilter());
            Assert.AreEqual(query.Diet, new DietFilter());
            Assert.AreEqual(query.Nutrition, new NutritionFilter());
            Assert.AreEqual(query.Skill, new SkillFilter());
            Assert.AreEqual(query.Taste, new TasteFilter());
        }
Example #2
0
 private void SearchRecipes(string query)
 {
     Query = new RecipeQuery {
         SearchTerm = string.IsNullOrEmpty(query) ? null : query
     };
     Refresh(Query);
 }
        public async Task <RecipeSearchResults> SearchRecipes(RecipeQuery query)
        {
            var recipes = await RecipeRepository.Search(query.SearchText);

            var results = new RecipeSearchResults
            {
                Recipes = new List <RecipeSearchResult>()
            };

            recipes.ToList().ForEach(r =>
            {
                ((List <RecipeSearchResult>)results.Recipes).Add(new RecipeSearchResult
                {
                    Id               = r.ID,
                    Description      = r.Description,
                    Name             = r.Title,
                    Url              = $"/api/recipe/{r.Key}",
                    ShortDescription = string.IsNullOrEmpty(r.ShortDescription) ? r.Description : r.ShortDescription,
                    Featured         = r.Featured,
                    Key              = r.Key
                });
            });

            return(results);
        }
Example #4
0
        public void RecipeQuery_Get_All_Succeeds()
        {
            var recipes = new RecipeQuery(_mockRepository.Object)
                          .Get();

            Assert.AreEqual(100, recipes.Count());
            Assert.IsTrue(recipes.All(r => r.Id >= 1 && r.Id <= 100));
        }
Example #5
0
        public SearchResults RecipeSearch(AuthIdentity identity, RecipeQuery query)
        {
            if (SearchProvider == null)
            {
                throw new NoConfiguredSearchProvidersException();
            }

            return(SearchProvider.Search(identity, query));
        }
Example #6
0
        private async void Refresh(RecipeQuery query)
        {
            var recipes = await _recipeService.SearchRecipesAsync(query);

            var items = recipes.Select(x => x.ToRecipeListItemViewModel(_messenger));

            Recipes = new ObservableCollection <RecipeListItemViewModel>(items);
            RaisePropertyChanged(() => IsEmpty);
        }
Example #7
0
 public static RecipeListParameters ToRecipeListParameters(this RecipeQuery query)
 {
     return(new RecipeListParameters
     {
         CategoryId = query.CategoryId.GetValueOrDefault(0),
         CategorySelected = query.CategoryId != null,
         IsFavoriteSelected = query.OnlyFavorite,
         SearchTerm = query.SearchTerm
     });
 }
        private void ListOfRecipeNames(RecipeQuery recipe)
        {
            int recipeNumber = 1;

            recipe.UserRecipes().ForEach(x =>
            {
                Console.WriteLine("nr {0}: {1}", recipeNumber, x.RecipeName);
                recipeNumber++;
            });
        }
Example #9
0
        public void RecipeActionSearch_ShouldReturnARecipeFinderWithCorrectValues()
        {
            var recipeQuery = new RecipeQuery();

            var recipeFinder = this.Action.Search(recipeQuery);

            Assert.IsInstanceOf(typeof(RecipeFinder), recipeFinder);
            Assert.AreSame(this.Context, recipeFinder.Context);
            Assert.AreSame(recipeQuery, recipeFinder.Query);
        }
Example #10
0
        public void RecipeQuery_Get_By_Id_Succeeds()
        {
            var recipe = new RecipeQuery(_mockRepository.Object)
                         .GetById(20);

            Assert.IsNotNull(recipe);
            Assert.AreEqual(20, recipe.Id);
            Assert.AreEqual("20", recipe.Title);
            Assert.AreEqual("Description: 20", recipe.Description);
            Assert.AreEqual(20, recipe.TimeToPrepare);
        }
        private void InsertBatch()
        {
            RecipeQuery recipe = new RecipeQuery();

            string[] listOfRecipeNames    = new string[10];
            string[] listOfPreparedBaches = new string[10];
            int      listIndex            = 0;

            Console.WriteLine("----Dodaj Zesatw----");
            Console.Write("Wpisz datę: ");
            string date = Console.ReadLine();

            DateTime date1 = StringToDateConverter(date);

            Console.WriteLine("Dostępne Receptury: ");
            ListOfRecipeNames(recipe);

            //Loop where you can write how meny batches where prepared
            while (true)
            {
                Console.Write("Nazwa receptury: ");
                string nameOfRecipe = Console.ReadLine();
                Console.Write("Ile Zestawów: ");
                string howMeny = Console.ReadLine();

                listOfRecipeNames[listIndex]    = nameOfRecipe;
                listOfPreparedBaches[listIndex] = howMeny;

                listIndex++;
                string com = Console.ReadLine();
                if (com == "q")
                {
                    break;
                }

                if (com == "r")
                {
                    ListOfRecipeNames(recipe);
                }
            }

            //Insert batches to DB
            for (int j = 0; j < listIndex; j++)
            {
                recipe.UserRecipes().ForEach(x =>
                {
                    if (listOfRecipeNames[j] == x.RecipeName)
                    {
                        query.InsertBatch(date1, x.GetID(), int.Parse(listOfPreparedBaches[j]));
                    }
                });
            }
        }
 private string GetTitle(RecipeQuery query)
 {
     if (query.OnlyFavorite)
     {
         return(Text.FavoritesLabel);
     }
     if (query.CategoryId != null)
     {
         var category = _referenceBook.LookupCategory(query.CategoryId.Value);
         return(category.Title);
     }
     return(Text.AllRecipesLabel);
 }
Example #13
0
        public void RecipeQueryClone_ShouldCloneObject()
        {
            var query = new RecipeQuery
            {
                Keywords  = "clone",
                Meal      = MealFilter.Breakfast,
                Rating    = Rating.OneStar,
                Sort      = SortOrder.CookTime,
                Direction = SortDirection.Ascending,
                Offset    = 3,
                Photos    = PhotoFilter.HighRes,
                Taste     =
                {
                    MildToSpicy   = SpicinessLevel.Spicy,
                    SavoryToSweet = SweetnessLevel.Sweet
                },
                Include = new Guid[] { Guid.NewGuid(), },
                Exclude = new Guid[] { Guid.NewGuid(), Guid.NewGuid() }
            };

            var clonedQuery = query.Clone() as RecipeQuery;

            Assert.AreEqual(query.Keywords, clonedQuery.Keywords);
            Assert.AreEqual(query.Meal, clonedQuery.Meal);
            Assert.AreEqual(query.Rating, clonedQuery.Rating);
            Assert.AreEqual(query.Sort, clonedQuery.Sort);
            Assert.AreEqual(query.Direction, clonedQuery.Direction);
            Assert.AreEqual(query.Offset, clonedQuery.Offset);
            Assert.AreEqual(query.Photos, clonedQuery.Photos);

            Assert.AreEqual(query.Time, clonedQuery.Time);
            Assert.AreNotSame(query.Time, clonedQuery.Time);

            Assert.AreEqual(query.Diet, clonedQuery.Diet);
            Assert.AreNotSame(query.Diet, clonedQuery.Diet);

            Assert.AreEqual(query.Nutrition, clonedQuery.Nutrition);
            Assert.AreNotSame(query.Nutrition, clonedQuery.Nutrition);

            Assert.AreEqual(query.Skill, clonedQuery.Skill);
            Assert.AreNotSame(query.Skill, clonedQuery.Skill);

            Assert.AreEqual(query.Taste, clonedQuery.Taste);
            Assert.AreNotSame(query.Taste, clonedQuery.Taste);

            CollectionAssert.AreEqual(query.Include, clonedQuery.Include);
            Assert.AreNotSame(query.Include, clonedQuery.Include);

            CollectionAssert.AreEqual(query.Exclude, clonedQuery.Exclude);
            Assert.AreNotSame(query.Exclude, clonedQuery.Exclude);
        }
        public async Task <string> GenerateShoppingCart(string words, string stores, Prj4databaseContext context)
        {
            string initString = "" +
                                "<html>";
            string endString = "</html>";

            string bodystring = "";

            string[] storeSplit = new string[8];

            if (stores != null)
            {
                storeSplit = stores.Split(';', StringSplitOptions.RemoveEmptyEntries);
            }

            RecipeQuery query = new RecipeQuery
            {
                LoadIngredientList = true,
                LoadRecipeCategory = true,
                SearchRecipe       = words,
                NumberOfRecipes    = 1,
                Stores             = storeSplit
            };

            RecipeRepository recipeRepository = new RecipeRepository(context);

            var result = await recipeRepository.Get(query);

            foreach (var recipe in result)
            {
                bodystring = "";
                string ingrediensstring = "";
                bodystring += "<h3><strong>Indkøbsliste</strong></h3>";

                bodystring += "<ul>";
                foreach (var ingredient in recipe.IngredientList.Ingredient)
                {
                    ingrediensstring += "<li class='p6'>" + ingredient.Name + " - " + " Købes i " + ingredient.Product.RetailChain.Name + " for " +
                                        ingredient.Product.Price + " kr. " + "</li>";
                }

                bodystring += ingrediensstring;
                bodystring += "</ul>" +
                              "</div>" +
                              "<br style='clear:both' />" +
                              "<ul>" +
                              "</div>";
            }
            return(initString + bodystring + endString);
        }
Example #15
0
        public void RecipeQuery_Get_Where_Succeeds()
        {
            var recipes = new RecipeQuery(_mockRepository.Object)
                          .GetWhere(new RecipeQueryOptions
            {
                TitleContains = "50"
            });

            Assert.IsNotNull(recipes);
            Assert.AreEqual(1, recipes.Count());

            var recipe = recipes.Single();

            Assert.AreEqual(50, recipe.Id);
            Assert.AreEqual(50, recipe.TimeToPrepare);
        }
Example #16
0
        public List <Recipe> SearchRecipes(RecipeQuery query)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(SearchService));
            }
            var parameters = new List <object>();
            var filters    = new List <string>();

            if (query.CategoryId != null)
            {
                filters.Add("(RecipeTextField.Type = 0 AND RecipeTextField.Value = ?)");
                parameters.Add(query.CategoryId.Value.ToString());
            }
            if (query.OnlyFavorite)
            {
                filters.Add("(RecipeTextField.Type = 1 AND RecipeTextField.Value LIKE '%Favorite%')");
            }
            if (!string.IsNullOrEmpty(query.SearchTerm))
            {
                var q = _parser.Parse(query.SearchTerm);
                parameters.Add(q);
                Mvx.Trace($"Query: {q}");
                filters.Add("RecipeTextSearch MATCH ?");
            }
            var filtersSql = filters.Count > 0
                ? $"WHERE {string.Join("AND", filters)}"
                : string.Empty;
            var sql     = $@"SELECT Recipe.Id, Recipe.Document, 
                        MIN(CASE RecipeTextField.Type
                            WHEN 2 THEN 0
                            WHEN 0 THEN 1
                            WHEN 1 THEN 2
                            WHEN 3 THEN 4
                            WHEN 5 THEN 6
	                        ELSE 7
                         END) AS Priority
                        FROM RecipeTextField
                        JOIN Recipe ON Recipe.Id = RecipeTextField.RecipeId
                        JOIN RecipeTextSearch ON RecipeTextSearch.docid = RecipeTextField.Id
                        {filtersSql}    
                        GROUP BY Recipe.Id
                        ORDER BY Priority";
            var recipes = _connection.Query <RecipeRow>(sql, parameters.ToArray());

            return(recipes.Select(x => x.ToRecipe(this)).ToList());
        }
Example #17
0
        public async Task GenerateCheapestPL()
        {
            RecipeQuery   rq         = new RecipeQuery();
            List <Recipe> recipeList = await GetListAsync("");

            List <string> distinctIngredients = rq.DistinctIngredients(recipeList);

            Dictionary <string, List <Product> > productsDictBilka = await rq.MatchingProductsChain(distinctIngredients, "Bilka");

            Dictionary <string, List <Product> > productsDictFakta = await rq.MatchingProductsChain(distinctIngredients, "Fakta");

            Dictionary <string, List <Product> > productsDictSuperBrugsen = await rq.MatchingProductsChain(distinctIngredients, "SuperBrugsen");

            await new DatabaseConnect().Recipe.InsertIngredientLink(productsDictBilka, "bilka");
            await new DatabaseConnect().Recipe.InsertIngredientLink(productsDictFakta, "fakta");
            await new DatabaseConnect().Recipe.InsertIngredientLink(productsDictSuperBrugsen, "superbrugsen");
        }
Example #18
0
        public void SetUp()
        {
            _uut = new RecipeQuery {
                LoadIngredientList = true
            };

            string ConnectionString = "Data Source=prj4-server.database.windows.net;Initial Catalog=prj4-database;User ID=maloudt;Password=Mldt1160";

            SqlConnection conn = new SqlConnection(ConnectionString);

            conn.Open();

            var options = new DbContextOptionsBuilder <Prj4databaseContext>()
                          .UseSqlServer(conn).Options;

            _context = new Prj4databaseContext(options);
        }
Example #19
0
        public async Task TestNormalPrice(string name)
        {
            RecipeQuery recipeQuery = new RecipeQuery
            {
                SearchRecipe       = name,
                LoadIngredientList = true,
                NumberOfRecipes    = 1,
            };

            var recipe = await recipeQuery.Execute(_context);

            string[] empty       = new string[8];
            double   resultTotal = await _uut.TotalPrice(recipe.First(), name, empty, _context);

            double resultNormal = await _uut.NormalPrice(recipe.First(), name, empty, _context);

            Assert.That(true, Is.EqualTo(resultNormal >= resultTotal));
        }
Example #20
0
        public void TestRecipeQueryConstructor()
        {
            var query = new RecipeQuery();

            CollectionAssert.AreEqual(query.Include, new Guid[0]);
            CollectionAssert.AreEqual(query.Exclude, new Guid[0]);
            Assert.AreEqual(query.Keywords, null);
            Assert.AreEqual(query.Meal, MealFilter.All);
            Assert.AreEqual(query.Photos, PhotoFilter.All);
            Assert.AreEqual(query.Rating, Rating.None);
            Assert.AreEqual(SortOrder.Rating, query.Sort);
            Assert.AreEqual(SortDirection.Descending, query.Direction);

            Assert.AreEqual(query.Time, new TimeFilter());
            Assert.AreEqual(query.Diet, new DietFilter());
            Assert.AreEqual(query.Nutrition, new NutritionFilter());
            Assert.AreEqual(query.Skill, new SkillFilter());
            Assert.AreEqual(query.Taste, new TasteFilter());
        }
        public void Init(RecipeDetailedListParameters parameters)
        {
            Recipes.Clear();
            _query = new RecipeQuery
            {
                CategoryId   = parameters.CategorySelected ? parameters.CategoryId : (int?)null,
                OnlyFavorite = parameters.IsFavoriteSelected,
                SearchTerm   = parameters.SearchTerm
            };
            var recipes = _recipeService.SearchRecipesAsync(_query).Result;

            foreach (var recipe in recipes)
            {
                Recipes.Add(recipe.ToRecipeDisplayViewModel());
            }
            var selected = Recipes.First(x => x.Id == parameters.RecipeId);
            var index    = Recipes.IndexOf(selected);

            SelectedRecipeIndex = index;
        }
Example #22
0
 public RecipeListViewModel(IRecipeCollectionService recipeService, IMvxMessenger messenger)
 {
     if (recipeService == null)
     {
         throw new ArgumentNullException(nameof(recipeService));
     }
     if (messenger == null)
     {
         throw new ArgumentNullException(nameof(messenger));
     }
     Query          = new RecipeQuery();
     _recipeService = recipeService;
     _messenger     = messenger;
     Recipes        = new ObservableCollection <RecipeListItemViewModel>();
     Subscriptions.AddRange(new List <IDisposable>
     {
         _messenger.Subscribe <RecipeAdded>(OnRecipeAdded),
         _messenger.Subscribe <RecipeFavoriteTagChanging>(OnRecipeFavoriteTagChanging),
         _messenger.Subscribe <RecipeFavoriteTagChanged>(OnRecipeFavoriteTagChanged),
         _messenger.Subscribe <RecipeUpdated>(OnRecipeUpdated),
         _messenger.Subscribe <RecipeRemoved>(OnRecipeRemoved),
     });
 }
        public SearchResults RecipeSearch(AuthIdentity identity, RecipeQuery query)
        {
            if (this.SearchProvider == null)
            {
                throw new NoConfiguredSearchProvidersException();
            }

            return this.SearchProvider.Search(identity, query);
        }
Example #24
0
        public SearchResults Search(AuthIdentity identity, RecipeQuery query)
        {
            using (var session = this.adapter.GetSession())
            {
                Recipes recipe = null;

                var q = session.QueryOver <Recipes>(() => recipe)
                        .Where(p => !p.Hidden);

                // Add keyword search
                if (!string.IsNullOrWhiteSpace(query.Keywords))
                {
                    q = q.Where(
                        Restrictions.Or(
                            Restrictions.InsensitiveLike("Title", string.Format("%{0}%", query.Keywords.Trim())),
                            Restrictions.InsensitiveLike("Description", string.Format("%{0}%", query.Keywords.Trim()))));
                }

                if (query.Time.MaxPrep.HasValue)
                {
                    q = q.Where(p => p.PrepTime <= query.Time.MaxPrep.Value);
                }

                if (query.Time.MaxCook.HasValue)
                {
                    q = q.Where(p => p.CookTime <= query.Time.MaxCook.Value);
                }

                if (query.Rating > 0)
                {
                    q = q.Where(p => p.Rating >= (int)query.Rating);
                }

                // Add ingredients to include
                if (query.Include != null && query.Include.Length > 0)
                {
                    // Create a sub-query for ingredients to include
                    q = q.WithSubquery
                        .WhereExists(QueryOver.Of <RecipeIngredients>()
                                     .Where(item => item.Recipe.RecipeId == recipe.RecipeId)
                                     .Where(Restrictions.InG("Ingredient", query.Include.Select(Models.Ingredients.FromId).ToArray()))
                                     .Select(i => i.RecipeIngredientId).Take(1));
                }

                // Add ingredients to exclude
                if (query.Exclude != null && query.Exclude.Length > 0)
                {
                    // Create a sub-query for ingredients to exclude
                    q = q.WithSubquery
                        .WhereNotExists(QueryOver.Of <RecipeIngredients>()
                                        .Where(item => item.Recipe.RecipeId == recipe.RecipeId)
                                        .Where(Restrictions.InG("Ingredient", query.Exclude.Select(Models.Ingredients.FromId).ToArray()))
                                        .Select(i => i.RecipeIngredientId).Take(1));
                }

                if (query.Photos == PhotoFilter.Photo || query.Photos == PhotoFilter.HighRes)
                {
                    q = q.Where(Restrictions.IsNotNull("ImageUrl"));
                }

                // Need to search in metadata
                if (query.Diet || query.Nutrition || query.Skill || query.Taste || (query.Meal != MealFilter.All) || (query.Photos == PhotoFilter.HighRes))
                {
                    RecipeMetadata metadata = null;
                    q = q.JoinAlias(r => r.RecipeMetadata, () => metadata);

                    // Meal
                    if (query.Meal != MealFilter.All)
                    {
                        if (query.Meal == MealFilter.Breakfast)
                        {
                            q = q.Where(() => metadata.MealBreakfast);
                        }

                        if (query.Meal == MealFilter.Dessert)
                        {
                            q = q.Where(() => metadata.MealDessert);
                        }

                        if (query.Meal == MealFilter.Dinner)
                        {
                            q = q.Where(() => metadata.MealDinner);
                        }

                        if (query.Meal == MealFilter.Lunch)
                        {
                            q = q.Where(() => metadata.MealLunch);
                        }
                    }

                    // High-res photos
                    if (query.Photos == PhotoFilter.HighRes)
                    {
                        q = q.Where(() => metadata.PhotoRes >= 1024 * 768);
                    }

                    // Diet
                    if (query.Diet.GlutenFree)
                    {
                        q = q.Where(() => metadata.DietGlutenFree);
                    }

                    if (query.Diet.NoAnimals)
                    {
                        q = q.Where(() => metadata.DietNoAnimals);
                    }

                    if (query.Diet.NoMeat)
                    {
                        q = q.Where(() => metadata.DietNomeat);
                    }

                    if (query.Diet.NoPork)
                    {
                        q = q.Where(() => metadata.DietNoPork);
                    }

                    if (query.Diet.NoRedMeat)
                    {
                        q = q.Where(() => metadata.DietNoRedMeat);
                    }

                    // Nutrition
                    if (query.Nutrition.LowCalorie)
                    {
                        q = q.Where(() => metadata.NutritionLowCalorie);
                    }

                    if (query.Nutrition.LowCarb)
                    {
                        q = q.Where(() => metadata.NutritionLowCarb);
                    }

                    if (query.Nutrition.LowFat)
                    {
                        q = q.Where(() => metadata.NutritionLowFat);
                    }

                    if (query.Nutrition.LowSodium)
                    {
                        q = q.Where(() => metadata.NutritionLowSodium);
                    }

                    if (query.Nutrition.LowSugar)
                    {
                        q = q.Where(() => metadata.NutritionLowSugar);
                    }

                    // Skill
                    if (query.Skill.Common)
                    {
                        q = q.Where(() => metadata.SkillCommon).OrderBy(() => metadata.Commonality).Desc();
                    }

                    if (query.Skill.Easy)
                    {
                        q = q.Where(() => metadata.SkillEasy);
                    }

                    if (query.Skill.Quick)
                    {
                        q = q.Where(() => metadata.SkillQuick);
                    }

                    // Taste
                    if (query.Taste.MildToSpicy != SpicinessLevel.Medium)
                    {
                        q = query.Taste.MildToSpicy < SpicinessLevel.Medium
                           ? q.Where(() => metadata.TasteMildToSpicy <= query.Taste.Spiciness).OrderBy(() => metadata.TasteMildToSpicy).Asc()
                           : q.Where(() => metadata.TasteMildToSpicy >= query.Taste.Spiciness).OrderBy(() => metadata.TasteMildToSpicy).Desc();
                    }

                    if (query.Taste.SavoryToSweet != SweetnessLevel.Medium)
                    {
                        q = query.Taste.SavoryToSweet < SweetnessLevel.Medium
                           ? q.Where(() => metadata.TasteSavoryToSweet <= query.Taste.Sweetness).OrderBy(() => metadata.TasteSavoryToSweet).Asc()
                           : q.Where(() => metadata.TasteSavoryToSweet >= query.Taste.Sweetness).OrderBy(() => metadata.TasteSavoryToSweet).Desc();
                    }
                }

                IQueryOverOrderBuilder <Recipes, Recipes> orderBy;
                switch (query.Sort)
                {
                case SortOrder.Title:
                    orderBy = q.OrderBy(p => p.Title);
                    break;

                case SortOrder.PrepTime:
                    orderBy = q.OrderBy(p => p.PrepTime);
                    break;

                case SortOrder.CookTime:
                    orderBy = q.OrderBy(p => p.CookTime);
                    break;

                case SortOrder.Image:
                    orderBy = q.OrderBy(p => p.ImageUrl);
                    break;

                default:
                    orderBy = q.OrderBy(p => p.Rating);
                    break;
                }

                var results = (query.Direction == SortDirection.Descending ? orderBy.Desc() : orderBy.Asc())
                              .Skip(query.Offset)
                              .List();

                return(new SearchResults
                {
                    Briefs = results.Select(r => r.AsRecipeBrief()).ToArray(),
                    TotalCount = results.Count
                });
            }
        }
Example #25
0
 public SearchResults RecipeSearch(RecipeQuery query)
 {
     this.RSCalledTimes++;
     this.search = query;
     return(new SearchResults());
 }
Example #26
0
        // GET: api/Recipes
        /// <summary>
        /// Gets all recipes or allows optional search parameters. All parameters are optional. If none are supplied then all recipes are returned
        /// </summary>
        /// <returns></returns>
        public IQueryable <RecipeDTO> GetRecipes([FromUri] RecipeQuery recipeQuery)
        {
            IQueryable <RecipeDTO> recipes;


            if (recipeQuery.HopId.IsNullOrEmpty() && recipeQuery.MaltId.IsNullOrEmpty())
            {
                recipes = from r in db.Recipes
                          select new RecipeDTO()
                {
                    Source2      = r.Source2,
                    Number       = r.Number,
                    Name         = r.Name,
                    YeastID      = r.YeastID,
                    YeastName    = r.Yeast.YeastName,
                    ID           = r.ID,
                    ABV          = r.ABV,
                    IBU          = r.IBU,
                    OG           = r.OG,
                    FG           = r.FG,
                    EBC          = r.EBC,
                    HasAdjucts   = r.HasAdjucts,
                    MashTemp     = r.MashTemp,
                    MashTime     = r.MashTime,
                    BoilTime     = r.BoilTime,
                    BatchSize    = r.BatchSize,
                    Fermentation = r.Fermentation
                };
            }
            else
            {
                recipes = from r in db.Recipes
                          select new RecipeDTO()
                {
                    Source2      = r.Source2,
                    Number       = r.Number,
                    Name         = r.Name,
                    YeastID      = r.YeastID,
                    YeastName    = r.Yeast.YeastName,
                    ID           = r.ID,
                    ABV          = r.ABV,
                    IBU          = r.IBU,
                    OG           = r.OG,
                    FG           = r.FG,
                    EBC          = r.EBC,
                    HasAdjucts   = r.HasAdjucts,
                    MashTemp     = r.MashTemp,
                    MashTime     = r.MashTime,
                    BoilTime     = r.BoilTime,
                    BatchSize    = r.BatchSize,
                    Fermentation = r.Fermentation,
                    Recipe_Hops  = r.Recipe_Hops.Select(rh => new Recipe_HopsDTO
                    {
                        ID       = rh.ID,
                        RecipeID = rh.RecipeID,
                        Weight   = rh.Weight,
                        HopID    = rh.HopID,
                        StepID   = rh.StepID,
                        HopName  = rh.Hop.Hops,
                        StepName = rh.HopStep.Step
                    }).ToList(),
                    Recipe_Malts = r.Recipe_Malts.Select(rm => new Recipe_MaltsDTO
                    {
                        ID              = rm.ID,
                        RecipeID        = rm.RecipeID,
                        Weight          = rm.Weight,
                        MaltGenericID   = rm.MaltGenericID,
                        MaltID          = rm.MaltID,
                        MaltGenericName = rm.MaltGeneric.Malt
                    }).ToList()
                };
            }

            if (recipeQuery.ABVMax != null)
            {
                recipes = recipes.Where(r => r.ABV <= recipeQuery.ABVMax);
            }

            if (recipeQuery.ABVMin != null)
            {
                recipes = recipes.Where(r => r.ABV >= recipeQuery.ABVMin);
            }

            if (recipeQuery.IBUMax != null)
            {
                recipes = recipes.Where(r => r.IBU <= recipeQuery.IBUMax);
            }

            if (recipeQuery.IBUMin != null)
            {
                recipes = recipes.Where(r => r.IBU >= recipeQuery.IBUMin);
            }

            if (recipeQuery.EBCMax != null)
            {
                recipes = recipes.Where(r => r.EBC <= recipeQuery.EBCMax);
            }

            if (recipeQuery.EBCMin != null)
            {
                recipes = recipes.Where(r => r.EBC >= recipeQuery.EBCMin);
            }

            if (recipeQuery.FermentMax != null)
            {
                recipes = recipes.Where(r => r.Fermentation <= recipeQuery.FermentMax);
            }

            if (recipeQuery.FermentMin != null)
            {
                recipes = recipes.Where(r => r.Fermentation >= recipeQuery.FermentMin);
            }

            if (recipeQuery.hasAdjuncts != null)
            {
                recipes = recipes.Where(r => r.HasAdjucts == recipeQuery.hasAdjuncts);
            }

            if (recipeQuery.YeastId.IsNullOrEmpty() == false)
            {
                recipes = recipes.Where(r => recipeQuery.YeastId.Contains(r.YeastID));
            }

            if (recipeQuery.MaltId.IsNullOrEmpty() == false)
            {
                recipes = recipes.Where(r => r.Recipe_Malts.Any(rm => recipeQuery.MaltId.Contains(rm.MaltGenericID)));
            }

            if (recipeQuery.HopId.IsNullOrEmpty() == false)
            {
                recipes = recipes.Where(r => r.Recipe_Hops.Any(rh => recipeQuery.HopId.Contains(rh.HopID)));
            }

            return(recipes);
        }
Example #27
0
        public SearchResults Search(AuthIdentity identity, RecipeQuery query)
        {
            using (var session = this.adapter.GetSession())
            {
                Recipes recipe = null;

                var q = session.QueryOver(() => recipe)
                   .Where(p => !p.Hidden);

                if (!string.IsNullOrWhiteSpace(query.Keywords))
                {
                    q = q.Where(
                        Restrictions.Or(
                            Restrictions.InsensitiveLike("Title", string.Format("%{0}%", query.Keywords.Trim())),
                            Restrictions.InsensitiveLike("Description", string.Format("%{0}%", query.Keywords.Trim()))));
                }

                if (query.Time.MaxPrep.HasValue)
                {
                    q = q.Where(p => p.PrepTime <= query.Time.MaxPrep.Value);
                }

                if (query.Time.MaxCook.HasValue)
                {
                    q = q.Where(p => p.CookTime <= query.Time.MaxCook.Value);
                }

                if (query.Rating > 0)
                {
                    q = q.Where(p => p.Rating >= (int)query.Rating.Value);
                }

                if (query.Include != null && query.Include.Length > 0)
                {
                    // Create a sub-query for ingredients to include
                    q = q.WithSubquery
                       .WhereExists(QueryOver.Of<RecipeIngredients>()
                          .Where(item => item.Recipe.RecipeId == recipe.RecipeId)
                          .Where(Restrictions.InG("Ingredient", query.Include.Select(Ingredients.FromId).ToArray()))
                          .Select(i => i.RecipeIngredientId).Take(1));
                }

                if (query.Exclude != null && query.Exclude.Length > 0)
                {
                    // Create a sub-query for ingredients to exclude
                    q = q.WithSubquery
                       .WhereNotExists(QueryOver.Of<RecipeIngredients>()
                          .Where(item => item.Recipe.RecipeId == recipe.RecipeId)
                          .Where(Restrictions.InG("Ingredient", query.Exclude.Select(Ingredients.FromId).ToArray()))
                          .Select(i => i.RecipeIngredientId).Take(1));
                }

                if (query.Photos == PhotoFilter.Photo || query.Photos == PhotoFilter.HighRes)
                {
                    q = q.Where(Restrictions.IsNotNull("ImageUrl"));
                }

                if (query.Diet || query.Nutrition || query.Skill || query.Taste || (query.Meal != MealFilter.All) || (query.Photos == PhotoFilter.HighRes))
                {
                    RecipeMetadata metadata = null;
                    q = q.JoinAlias(r => r.RecipeMetadata, () => metadata);

                    if (query.Meal != MealFilter.All)
                    {
                        if (query.Meal == MealFilter.Breakfast)
                        {
                            q = q.Where(() => metadata.MealBreakfast);
                        }

                        if (query.Meal == MealFilter.Dessert)
                        {
                            q = q.Where(() => metadata.MealDessert);
                        }

                        if (query.Meal == MealFilter.Dinner)
                        {
                            q = q.Where(() => metadata.MealDinner);
                        }

                        if (query.Meal == MealFilter.Lunch)
                        {
                            q = q.Where(() => metadata.MealLunch);
                        }
                    }

                    if (query.Photos == PhotoFilter.HighRes)
                    {
                        q = q.Where(() => metadata.PhotoRes >= 1024 * 768);
                    }

                    if (query.Diet.GlutenFree)
                    {
                        q = q.Where(() => metadata.DietGlutenFree);
                    }

                    if (query.Diet.NoAnimals)
                    {
                        q = q.Where(() => metadata.DietNoAnimals);
                    }

                    if (query.Diet.NoMeat)
                    {
                        q = q.Where(() => metadata.DietNomeat);
                    }

                    if (query.Diet.NoPork)
                    {
                        q = q.Where(() => metadata.DietNoPork);
                    }

                    if (query.Diet.NoRedMeat)
                    {
                        q = q.Where(() => metadata.DietNoRedMeat);
                    }

                    if (query.Nutrition.LowCalorie)
                    {
                        q = q.Where(() => metadata.NutritionLowCalorie);
                    }

                    if (query.Nutrition.LowCarb)
                    {
                        q = q.Where(() => metadata.NutritionLowCarb);
                    }

                    if (query.Nutrition.LowFat)
                    {
                        q = q.Where(() => metadata.NutritionLowFat);
                    }

                    if (query.Nutrition.LowSodium)
                    {
                        q = q.Where(() => metadata.NutritionLowSodium);
                    }

                    if (query.Nutrition.LowSugar)
                    {
                        q = q.Where(() => metadata.NutritionLowSugar);
                    }

                    if (query.Skill.Common)
                    {
                        q = q.Where(() => metadata.SkillCommon).OrderBy(() => metadata.Commonality).Desc();
                    }

                    if (query.Skill.Easy)
                    {
                        q = q.Where(() => metadata.SkillEasy);
                    }

                    if (query.Skill.Quick)
                    {
                        q = q.Where(() => metadata.SkillQuick);
                    }

                    if (query.Taste.MildToSpicy != SpicinessLevel.Medium)
                    {
                        q = query.Taste.MildToSpicy < SpicinessLevel.Medium
                           ? q.Where(() => metadata.TasteMildToSpicy <= query.Taste.Spiciness).OrderBy(() => metadata.TasteMildToSpicy).Asc()
                           : q.Where(() => metadata.TasteMildToSpicy >= query.Taste.Spiciness).OrderBy(() => metadata.TasteMildToSpicy).Desc();
                    }

                    if (query.Taste.SavoryToSweet != SweetnessLevel.Medium)
                    {
                        q = query.Taste.SavoryToSweet < SweetnessLevel.Medium
                           ? q.Where(() => metadata.TasteSavoryToSweet <= query.Taste.Sweetness).OrderBy(() => metadata.TasteSavoryToSweet).Asc()
                           : q.Where(() => metadata.TasteSavoryToSweet >= query.Taste.Sweetness).OrderBy(() => metadata.TasteSavoryToSweet).Desc();
                    }
                }

                IQueryOverOrderBuilder<Recipes, Recipes> orderBy;

                switch (query.Sort)
                {
                    case SortOrder.Title:
                        orderBy = q.OrderBy(p => p.Title);
                        break;
                    case SortOrder.PrepTime:
                        orderBy = q.OrderBy(p => p.PrepTime);
                        break;
                    case SortOrder.CookTime:
                        orderBy = q.OrderBy(p => p.CookTime);
                        break;
                    case SortOrder.Image:
                        orderBy = q.OrderBy(p => p.ImageUrl);
                        break;
                    default:
                        orderBy = q.OrderBy(p => p.Rating);
                        break;
                }

                var results = (query.Direction == SortDirection.Descending ? orderBy.Desc() : orderBy.Asc())
                   .Skip(query.Offset)
                   .Take(100)
                   .List();

                return new SearchResults
                {
                    Briefs = results.Select(r => r.AsRecipeBrief()).ToArray(),
                    TotalCount = results.Count
                };
            }
        }
Example #28
0
        public Results Search(RecipeQuery recipeQuery)
        {
            Results results = null;

            // create query
            var query = _queryBuilder.CreateFromRecipeQuery(recipeQuery);

            // query
            var queryResults = _queryEngine.ExecuteQuery(query);

            // create results
            results = _resultsConverter.CreateFromProviderResults(queryResults);

            return results;
        }
Example #29
0
        public SearchResults Search(AuthIdentity identity, RecipeQuery query)
        {
            var index = store.GetSearchIndex();

            var q = index.Where(p => !p.Recipe.Hidden);

            if (!String.IsNullOrWhiteSpace(query.Keywords))
            {
                q = q.Where(p =>
                            (p.Recipe.Title ?? "").IndexOf(query.Keywords, StringComparison.OrdinalIgnoreCase) >= 0 ||
                            (p.Recipe.Description ?? "").IndexOf(query.Keywords, StringComparison.OrdinalIgnoreCase) >= 0
                            );
            }

            if (query.Time.MaxPrep.HasValue)
            {
                q = q.Where(p => p.Recipe.PrepTime <= query.Time.MaxPrep.Value);
            }

            if (query.Time.MaxCook.HasValue)
            {
                q = q.Where(p => p.Recipe.CookTime <= query.Time.MaxCook.Value);
            }

            if (query.Rating > 0)
            {
                q = q.Where(p => p.Recipe.Rating >= (int)query.Rating);
            }

            if (query.Include != null && query.Include.Length > 0) // Add ingredients to include
            {
                q = q.Where(p => p.Ingredients.Any(i => query.Include.Contains(i.IngredientId)));
            }

            if (query.Exclude != null && query.Exclude.Length > 0) // Add ingredients to exclude
            {
                q = q.Where(p => !p.Ingredients.Any(i => query.Exclude.Contains(i.IngredientId)));
            }

            if (query.Photos == PhotoFilter.Photo || query.Photos == PhotoFilter.HighRes)
            {
                q = q.Where(p => p.Recipe.ImageUrl != null);
            }

            if (query.Diet || query.Nutrition || query.Skill || query.Taste || (query.Meal != MealFilter.All) || (query.Photos == PhotoFilter.HighRes)) //Need to search in metadata
            {
                //Meal
                if (query.Meal != MealFilter.All)
                {
                    if (query.Meal == MealFilter.Breakfast)
                    {
                        q = q.Where(p => p.Metadata.MealBreakfast);
                    }
                    if (query.Meal == MealFilter.Dessert)
                    {
                        q = q.Where(p => p.Metadata.MealDessert);
                    }
                    if (query.Meal == MealFilter.Dinner)
                    {
                        q = q.Where(p => p.Metadata.MealDinner);
                    }
                    if (query.Meal == MealFilter.Lunch)
                    {
                        q = q.Where(p => p.Metadata.MealLunch);
                    }
                }

                //High-res photos
                if (query.Photos == PhotoFilter.HighRes)
                {
                    q = q.Where(p => p.Metadata.PhotoRes >= 1024 * 768);
                }

                //Diet
                if (query.Diet.GlutenFree)
                {
                    q = q.Where(p => p.Metadata.DietGlutenFree);
                }
                if (query.Diet.NoAnimals)
                {
                    q = q.Where(p => p.Metadata.DietNoAnimals);
                }
                if (query.Diet.NoMeat)
                {
                    q = q.Where(p => p.Metadata.DietNomeat);
                }
                if (query.Diet.NoPork)
                {
                    q = q.Where(p => p.Metadata.DietNoPork);
                }
                if (query.Diet.NoRedMeat)
                {
                    q = q.Where(p => p.Metadata.DietNoRedMeat);
                }

                //Nutrition
                if (query.Nutrition.LowCalorie)
                {
                    q = q.Where(p => p.Metadata.NutritionLowCalorie);
                }
                if (query.Nutrition.LowCarb)
                {
                    q = q.Where(p => p.Metadata.NutritionLowCarb);
                }
                if (query.Nutrition.LowFat)
                {
                    q = q.Where(p => p.Metadata.NutritionLowFat);
                }
                if (query.Nutrition.LowSodium)
                {
                    q = q.Where(p => p.Metadata.NutritionLowSodium);
                }
                if (query.Nutrition.LowSugar)
                {
                    q = q.Where(p => p.Metadata.NutritionLowSugar);
                }

                //Skill
                if (query.Skill.Common)
                {
                    q = q.Where(p => p.Metadata.SkillCommon).OrderByDescending(p => p.Metadata.Commonality);
                }
                if (query.Skill.Easy)
                {
                    q = q.Where(p => p.Metadata.SkillEasy);
                }
                if (query.Skill.Quick)
                {
                    q = q.Where(p => p.Metadata.SkillQuick);
                }

                //Taste
                if (query.Taste.MildToSpicy != SpicinessLevel.Medium)
                {
                    q = query.Taste.MildToSpicy < SpicinessLevel.Medium
                  ? q.Where(p => p.Metadata.TasteMildToSpicy <= query.Taste.Spiciness).OrderBy(p => p.Metadata.TasteMildToSpicy)
                  : q.Where(p => p.Metadata.TasteMildToSpicy >= query.Taste.Spiciness).OrderByDescending(p => p.Metadata.TasteMildToSpicy);
                }

                if (query.Taste.SavoryToSweet != SweetnessLevel.Medium)
                {
                    q = query.Taste.SavoryToSweet < SweetnessLevel.Medium
                  ? q.Where(p => p.Metadata.TasteSavoryToSweet <= query.Taste.Sweetness).OrderBy(p => p.Metadata.TasteSavoryToSweet)
                  : q.Where(p => p.Metadata.TasteSavoryToSweet >= query.Taste.Sweetness).OrderByDescending(p => p.Metadata.TasteSavoryToSweet);
                }
            }

            switch (query.Sort)
            {
            case SortOrder.Title:
                q = (query.Direction == SortDirection.Ascending) ? q.OrderBy(p => p.Recipe.Title) : q.OrderByDescending(p => p.Recipe.Title);
                break;

            case SortOrder.PrepTime:
                q = (query.Direction == SortDirection.Ascending) ? q.OrderBy(p => p.Recipe.PrepTime) : q.OrderByDescending(p => p.Recipe.PrepTime);
                break;

            case SortOrder.CookTime:
                q = (query.Direction == SortDirection.Ascending) ? q.OrderBy(p => p.Recipe.CookTime) : q.OrderByDescending(p => p.Recipe.CookTime);
                break;

            case SortOrder.Image:
                q = (query.Direction == SortDirection.Ascending) ? q.OrderBy(p => p.Recipe.ImageUrl) : q.OrderByDescending(p => p.Recipe.ImageUrl);
                break;

            default:
                q = (query.Direction == SortDirection.Ascending) ? q.OrderBy(p => p.Recipe.Rating) : q.OrderByDescending(p => p.Recipe.Rating);
                break;
            }

            return(new SearchResults
            {
                Briefs = q.Select(r => Data.DTO.Recipes.ToRecipeBrief(r.Recipe)).ToArray(),
                TotalCount = q.Count()
            });
        }
Example #30
0
 public void RestoreState(RecipeListParameters parameters)
 {
     Query = parameters == null ? new RecipeQuery() : parameters.ToQuery();
     Refresh(Query);
 }
Example #31
0
 public void Init(RecipeListParameters parameters)
 {
     Query = parameters == null ? new RecipeQuery() : parameters.ToQuery();
     Refresh(Query);
 }
 public Results SearchRecipes(RecipeQuery recipeQuery)
 {
     return _searcher.Search(recipeQuery, null);
 }
Example #33
0
        static void Main(string[] args)
        {
            prj4databaseContext context = new prj4databaseContext();
            RecipeQuery         test    = new RecipeQuery
            {
                LoadIngredientList = true,
                LoadSubscriptions  = true,
                SearchRecipe       = "vegetar"
            };

            var udskrift = test.Execute(context);

            foreach (var VARIABLE in udskrift.Result)
            {
                Console.WriteLine($"{VARIABLE.Name}");
            }



            //foreach (var VARIABLE in udskrift)
            //{
            //    Console.WriteLine($"{VARIABLE}");
            //}
            //Console.WriteLine("Hello World!");

            //prj4databaseContext context = new prj4databaseContext();
            //VareRepository objekt = new VareRepository(context);

            //Vare var1 = new Vare();
            ////var1.VareId = 50000;
            //var1.Navn = "Testvare";
            //var1.Pris = 2000.0;
            //var1.Butik = "Netto";
            //var1.ValidFra = "";
            //var1.ValidTil = "";
            //var1.Volumenpris = 100;
            //var1.Volumen = 200;
            //var1.Imgsrc = "";

            //objekt.InsertVare(var1);
            //objekt.Save();

            /*
             * prj4databaseContext context = new prj4databaseContext();
             * RecipesRepository repo = new RecipesRepository(context);
             * IngredientList liste = new IngredientList();
             * Vare v1 = new Vare();
             * v1.Navn = "Kødboller";
             * v1.Pris = 45;
             * v1.Butik = "Rema2000";
             * v1.ValidFra = "";
             * v1.ValidTil = "";
             * v1.Volumenpris = 45;
             * v1.Volumen = 1000;
             * v1.Imgsrc = "";
             *
             * Vare v2 = new Vare();
             * v1.Navn = "Fiskefillet";
             * v1.Pris = 21;
             * v1.Butik = "Rema23000";
             * v1.ValidFra = "";
             * v1.ValidTil = "";
             * v1.Volumenpris = 30;
             * v1.Volumen = 450;
             * v1.Imgsrc = "";
             * liste.IngredientId = 2000;
             *
             * Recipes recipe = new Recipes();
             *
             * recipe.Category = "Vegetar";
             * recipe.Directions = "1. Put ting i en skål. 2. Rør dem sammen. 3. Put det i en spand. 4. Spis med glæde!";
             * recipe.IngredientList = new List<IngredientList>();
             * recipe.Name = "VegetarMedKød";
             * recipe.Price = 45;
             * recipe.SavingsAbsolute = 20;
             * recipe.SavingsPercent = 10;
             * recipe.Servings = 2;
             * recipe.Subscriptions = new List<Subscriptions>();
             * recipe.Timestamp = DateTime.Now;
             *
             * repo.InsertRecipe(recipe);
             * repo.Save();
             */
        }
 public Results SearchRecipes(RecipeQuery recipeQuery, RecipeQueryExtension extension)
 {
     return _searcher.Search(recipeQuery, extension);
 }
 public RecipeQueryBuilder(RecipeQuery query)
 {
     this.query = query;
 }
Example #36
0
 public string CreateFromRecipeQuery(RecipeQuery recipeQuery)
 {
     throw new NotImplementedException();
 }