Ejemplo n.º 1
0
        public async Task RecipeUpdate_ClearingAllIngredients_AreDeleted()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options);

                using (var context = new RecipesContext(options))
                {
                    var service        = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipeToUpdate = await service.GetOne(4);

                    // Remove all ingredients
                    recipeToUpdate.Ingredients = new List <IngredientBase>();
                    await service.UpdateOne(recipeToUpdate);

                    var dbrecipe = await service.GetOne(4);

                    //Assert.IsFalse(dbrecipe.Ingredients.Any());
                    Assert.AreEqual(0, dbrecipe.Ingredients.Count());
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public async Task TestUpdatesRecipeWithoutIngredients()
        {
            DatabaseFixture fixture             = new DatabaseFixture();
            var             options             = fixture.options;
            var             recipesContext      = new RecipesContext(options);
            var             emptyIngredientList = new List <Ingredient>();
            var             existingIngredient  = new Recipe
            {
                Description = "existing description", Name = "existing title", Ingredients = emptyIngredientList, Id = 9
            };
            await recipesContext.Recipes.AddAsync(existingIngredient);

            await recipesContext.SaveChangesAsync();

            var controller = new RecipesController(recipesContext);

            var emptyList = Array.Empty <IngredientDto>();
            var newRecipe = new RecipeDto("Updated recipe", "Updated description", emptyList)
            {
                Id = 9
            };
            await controller.PatchRecipe(9, newRecipe);

            var updatedRecipe = await recipesContext.Recipes.FindAsync((long)9);

            Assert.Equal("Updated recipe", updatedRecipe.Name);
            Assert.Equal("Updated description", updatedRecipe.Description);
            Assert.Empty(updatedRecipe.Ingredients);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            using (var context = new RecipesContext())
            {
                var parentRecipe = new Recipe {
                    RecipeName = "another parent recipe"
                };
                var parentIngredient = new RecipeIngredient {
                    Preparation = "parent's ingredient"
                };
                parentRecipe.RecipeIngredients.Add(parentIngredient);

                var childRecipe = new Recipe {
                    RecipeName = "child recipe"
                };
                var childIngredient = new RecipeIngredient {
                    Preparation = "child's ingredient"
                };
                childRecipe.RecipeIngredients.Add(childIngredient);


                context.Recipes.Add(parentRecipe);
                context.RecipeIngredients.Add(childIngredient);
                context.SaveChanges();
            }
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, RecipesContext recipesContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            recipesContext.CreateSeedData();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 5
0
        public bool DeleteRecipe(int recipeID, out string msg)
        {
            using (RecipesContext context = new RecipesContext())
            {
                try
                {
                    var toDelRecipe = (from r in context.Recipes select r)
                                      .Where(r => r.RecipeID == recipeID).Single();
                    var toDelIngredients = (from ing in context.Ingredients select ing)
                                           .Where(ing => ing.Recipe_RecipeID == recipeID);
                    foreach (var ing in toDelIngredients)
                    {
                        context.Ingredients.Remove(ing);
                    }
                    context.Recipes.Remove(toDelRecipe);
                } catch (InvalidOperationException e)
                {
                    msg = e.Message + ": no Recipe item exists\n" + "Please, use Refresh button!\n";
                    return(false);
                }
                context.SaveChanges();
            }

            FillRecipe();
            msg = "Deleted 1 Recipe item";
            return(true);
        }
Ejemplo n.º 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RecipesContext recContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            //app.UseHttpsRedirection();

            app.UseRouting();


            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            DBInitializer.Initialize(recContext);
        }
Ejemplo n.º 7
0
        public void FillRecipe()
        {
            ObservableCollection <Recipe> res = new ObservableCollection <Recipe>();

            using (RecipesContext context = new RecipesContext()) {
                var q = (from r in context.Recipes
                         select r).Include(r => r.Ingredients).ToList();

                foreach (var r in q)
                {
                    ObservableCollection <Ingredient> ingredients = new ObservableCollection <Ingredient>();
                    foreach (var ing in r.Ingredients)
                    {
                        ingredients.Add(ing);
                    }
                    switch (r.RecipeType.Trim())
                    {
                    case "Meal Item":
                        res.Add(new MealItem {
                            RecipeID = r.RecipeID, Title = r.Title, RecipeType = "Meal Item", Yield = r.Yield, ServingSize = r.ServingSize, Directions = r.Directions, Comment = r.Comment, Ingredients = ingredients
                        });
                        break;

                    case "Dessert":
                        res.Add(new Dessert {
                            RecipeID = r.RecipeID, Title = r.Title, RecipeType = "Dessert", Yield = r.Yield, ServingSize = r.ServingSize, Directions = r.Directions, Comment = r.Comment, Ingredients = ingredients
                        });
                        break;
                    }
                }

                Recipes = res;
            }
        }
Ejemplo n.º 8
0
        public bool AddRecipe(Recipe r, out string msg)
        {
            StringBuilder msgB = new StringBuilder();

            try
            {
                using (RecipesContext context = new RecipesContext())
                {
                    context.Recipes.Add(r);
                    foreach (var item in r.Ingredients)
                    {
                        context.Ingredients.Add(item);
                    }
                    context.SaveChanges();
                }
            } catch (DbEntityValidationException dbEx) {
                foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors)
                {
                    foreach (DbValidationError error in entityErr.ValidationErrors)
                    {
                        msgB.Append(error.PropertyName + ": " + error.ErrorMessage + "\n");
                    }
                }
                msgB.Append("Please, select or fill the required informations.");
                msg = msgB.ToString();
                return(false);
            }
            msg = "Saved a Recipe: " + r.Title;
            return(true);
        }
Ejemplo n.º 9
0
        private void SeedRootRecipies(RecipesContext context)
        {
            var rootRecipies = new[]
            {
                "Pasta Carbonara",
                "Mac & Cheese",
                "Baked Trout",
                "British Fries",
                "Mashed Potatoes",
                "New York Pizza",
                "Tortellini",
                "Classic Taco",
                "Salmon Pate",
                "Chicken Kyiv"
            };

            for (int i = 1; i < 11; i++)
            {
                var created = DateTime.Now;
                context.RecipesTree.Add(new RecipeNode()
                {
                    RecipeID     = i,
                    AncestryPath = i + "/",
                    Created      = created
                });
                context.RecipesHistory.Add(new RecipeLogEntry()
                {
                    VersionID   = i,
                    RecipeID    = i,
                    LastUpdated = created,
                    Title       = rootRecipies[i - 1],
                    Description = "Description for " + rootRecipies[i - 1]
                });
            }
        }
Ejemplo n.º 10
0
        // TODO: Nope. This should be a class with IDisposable. See 4:02 of Chapter 9 - refactoring.
        // SO that it can be called temporarily for a test
        public static async Task <RecipesContext> GetRecipesContext()
        {
            var options = new DbContextOptionsBuilder <RecipesContext>()
                          .UseInMemoryDatabase("TestContext")
                          .EnableSensitiveDataLogging()
                          .Options;
            var recipeContext = new RecipesContext(options);

            recipeContext.Database.EnsureCreated();
            if (await recipeContext.Recipes.CountAsync() <= 0)
            {
                // todo: use AddRange()
                for (int i = 1; i <= 5; i++)
                {
                    recipeContext.Recipes.Add(new Recipe()
                    {
                        Id           = i,
                        TitleLong    = (i % 2 == 0) ? $"LongTitle{i}" : String.Empty,
                        TitleShort   = $"ShortTitle{i}",
                        Description  = String.Empty,
                        LastModifier = $"testuser{i}@example.com",
                        OriginalLink = "",
                        AuditDate    = new DateTime(2019, 12, 03),
                        CreationDate = new DateTime(),
                        Ingredients  = new List <Ingredient> {
                            new Ingredient {
                                Id = 0, Name = $"Ingredient{i}", Quantity = 4, Unit_Id = 2
                            }
                        }
                    });
                    await recipeContext.SaveChangesAsync();
                }
            }
            return(recipeContext);
        }
Ejemplo n.º 11
0
        public async Task DeleteRecipeWithoutIngredients()
        {
            var options             = _fixture.Options;
            var recipesContext      = new RecipesContext(options);
            var controller          = CreateRecipesController(recipesContext);
            var emptyIngredientList = new List <Ingredient>();

            // add recipe to context
            var existingRecipe = new Recipe
            {
                Name        = "existing title",
                Description = "existing description",
                Ingredients = emptyIngredientList,
                Id          = 8
            };

            recipesContext.Recipes.Add(existingRecipe);

            var result = await controller.DeleteRecipe(8);

            Assert.IsType <NoContentResult>(result);

            var deletedRecipe = await recipesContext.Recipes.FindAsync((long)8);

            Assert.Null(deletedRecipe);
        }
Ejemplo n.º 12
0
        public async Task TestUpdatesRecipeWithoutIngredients()
        {
            var options             = _fixture.Options;
            var recipesContext      = new RecipesContext(options);
            var controller          = CreateRecipesController(recipesContext);
            var emptyIngredientList = new List <Ingredient>();
            var existingRecipe      = new Recipe
            {
                Name        = "existing title",
                Description = "existing description",
                Ingredients = emptyIngredientList,
                Id          = 9
            };
            await recipesContext.Recipes.AddAsync(existingRecipe);

            await recipesContext.SaveChangesAsync();

            var emptyList = new List <UpdatedIngredientDto>();
            var newRecipe = new UpdatedRecipeDto("Updated recipe", "Updated description", emptyList, 9);

            var result = await controller.PatchRecipe(9, newRecipe);

            Assert.IsType <ActionResult <Recipe> >(result);
            Assert.Equal("Updated recipe", result.Value.Name);
            Assert.Equal("Updated description", result.Value.Description);
            Assert.Empty(result.Value.Ingredients);
        }
Ejemplo n.º 13
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            var db = new RecipesContext();

            string encrypted = EncrypterDecrypter.Instance.Encrypt(context.Password, User.ENCRYPT_PASSWORD);

            var user = db.Users.FirstOrDefault(u => u.UserName == context.UserName && u.Password ==
                                               encrypted);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ApplicationUser appUser       = new ApplicationUser(user);
            ClaimsIdentity  oAuthIdentity = await appUser.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await appUser.GenerateUserIdentityAsync(userManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Ejemplo n.º 14
0
        public void XMLRecipesDescendentsShouldMatchDatabaseRows()
        {
            RecipesContext context               = new RecipesContext();
            int            dbRecipesRows         = context.Recipes.Count();
            int            xmlRecipesDescendants = RecipesContextInitializer.GetRecipeDataFromXDocument(XMLFileFinder.GetXMLRecipesPath()).Count;

            Assert.AreEqual(dbRecipesRows, xmlRecipesDescendants);
        }
Ejemplo n.º 15
0
        static RecipesContext getDbContext()
        {
            var context = new RecipesContext();

            context.Configuration.AutoDetectChangesEnabled = false;
            context.Database.CommandTimeout = 120;
            return(context);
        }
Ejemplo n.º 16
0
        private RecipesController CreateRecipesController(RecipesContext recipesContext)
        {
            var databaseActions  = new DatabaseActions(recipesContext);
            var ingredientDomain = new IngredientDomain(databaseActions);
            var recipesDomain    = new RecipesDomain(databaseActions, ingredientDomain);

            return(new RecipesController(recipesDomain));
        }
Ejemplo n.º 17
0
        public async Task RecipeUpdate_UpdatingExistingImageBytes_UpdatesProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 3;
                // Setup context with one recipe, and medias. Specifying separate media path since modifying image physically (to avoid conflict with other tests)
                SetupBasicContext(options, false, recipeId, "RecipeUpdate_UpdatingExistingImageBytes");

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID 4
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // Update media with ID: 1
                    var media = recipeToUpdate.Medias.Where(m => m.Id == 3).First();
                    // overriding ingredient to remove linked/tracked objects, and modifying some properties
                    // TODO: verify why object is being tracked? When we have asNoTracking set
                    recipeToUpdate.Medias.Remove(media);

                    // Load images json and select image 1 (foodMarket.jpg) that we know isn't in Media with ID 1 (foodColor.jpeg)
                    var TestImages = LoadRecipeMediaDtoFromJson(recipeId);
                    // Update properties AND mediabytes
                    recipeToUpdate.Medias.Add(new MediaDto {
                        Id = media.Id, Recipe_Id = media.Recipe_Id, Title = "FoodMarket", Tag = media.Tag, MediaDataUrl = TestImages.First().MediaDataUrl
                    });
                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    var image = recipeUpdated.Medias.Where(m => m.Id == 3).First();
                    Assert.AreEqual("FoodMarket", image.Title);

                    // Verify logger wrote INFO specifying that Media with Id 1 had its image overriden
                    this._loggerMock.Verify(l =>
                                            l.Log(LogLevel.Information, 0, It.Is <It.IsAnyType>((v, t) => v.ToString().Contains("New image provided")), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>())
                                            , Times.Once);
                    //l.Log(LogLevel.Information, 0, It.IsAny<It.IsAnyType>(), It.IsAny<Exception>(), (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 18
0
        public async Task RecipeUpdate_AddingNewImagesToRecipeWithNoImages_WorksAndPathCreatedProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 1; // TODO: why is this text conflicting with DeleteMultipleImages ? Not same path nor Recipe ID and diff contexts
                // Setup context with one recipe, no medias
                SetupBasicContext(options, true, recipeId);

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID setup for this test suite
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // loading 3 mediaDtos from json
                    var mediaDtos = LoadRecipeMediaDtoFromJson(recipeId);
                    // insert into recipe that we want to update, to act like incoming media bytes
                    recipeToUpdate.Medias = mediaDtos;

                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);

                    // Get recipe again from DB with new medias
                    var recipeToUpdate = await service.GetOne(recipeId);

                    Assert.AreEqual(3, recipeToUpdate.Medias.Count());
                    string userRecipePath; // not needed so we override
                    foreach (var i in recipeToUpdate.Medias)
                    {
                        var savedImgPath = MediaLogicHelper.GenerateSingleMediaPath(this._mediaHelper.UserMediasPath, recipeToUpdate.Id, i.Id, out userRecipePath);
                        // check file exists
                        Assert.IsTrue(File.Exists(savedImgPath));

                        long savedImageSize = new FileInfo(savedImgPath).Length;
                        // verify size is under 800kb
                        Assert.Less(savedImageSize, this.MAX_IMAGESIZE);
                    }
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 19
0
        public async Task RecipeUpdate_DeletingOneImage_DeletesProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 4; // choose recipe ID not used by other test to prevent conflicts on result checks
                // Setup context with one recipe, and medias. Specifying separate media path since modifying image physically (to avoid conflict with other tests)
                // TODO: Each test should have their own data to work with
                SetupBasicContext(options, false, recipeId, "RecipeUpdate_DeletingOneImage");

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID defined at class level
                    // TODO: we're doing all of this wrong... You need a moqed environment for all test to work properly... The mediaLogicHelperTest already handles testing physical loading

                    var recipeToUpdate = await service.GetOne(recipeId);

                    // Remove media with ID: 3
                    var image = recipeToUpdate.Medias.Where(m => m.Id == 3).First();
                    recipeToUpdate.Medias.Remove(image);


                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    var image = recipeUpdated.Medias.Where(m => m.Id == 3).FirstOrDefault();
                    Assert.IsNull(image);
                    Assert.AreEqual(2, recipeUpdated.Medias.Count, "Medias count should be 2");
                    // Verify logger wrote INFO specifying that Image 3 was deleted
                    this._loggerMock.Verify(l =>
                                            l.Log(LogLevel.Information, 0, It.Is <It.IsAnyType>((v, t) => v.ToString().Contains("DELETED") && v.ToString().Contains("ID:3")), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>())
                                            , Times.Once);
                    // verify file no longer exist
                    // File path was defined in SetupBasicContext, it's not following regular path standards (from recipe service)
                    var imgToDeletePath = this._contextMedia.Where(m => m.Id == 3).First().MediaPath;
                    Assert.IsFalse(File.Exists(imgToDeletePath));
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 20
0
        public bool UpdateRecipe(Recipe recipe, out string msg)
        {
            using (RecipesContext context = new RecipesContext())
            {
                try
                {
                    var toUpdateRecipe = context.Recipes.Where(r => r.RecipeID == recipe.RecipeID).Single();
                    //var toUpdateRecipe = (from r in context.Recipes select r)
                    //                 .Where(r => r.RecipeID == recipe.RecipeID).Single();
                    toUpdateRecipe.Title       = recipe.Title;
                    toUpdateRecipe.RecipeType  = recipe.RecipeType;
                    toUpdateRecipe.Yield       = recipe.Yield;
                    toUpdateRecipe.ServingSize = recipe.ServingSize;
                    toUpdateRecipe.Comment     = recipe.Comment;
                    toUpdateRecipe.Directions  = recipe.Directions;

                    var toDelIngredients = (from ing in context.Ingredients select ing)
                                           .Where(ing => ing.Recipe_RecipeID == recipe.RecipeID);

                    foreach (var ing in toDelIngredients)
                    {
                        context.Ingredients.Remove(ing);
                    }
                    foreach (var ing in recipe.Ingredients)
                    {
                        context.Ingredients.Add(new Ingredient {
                            Description = ing.Description, Recipe = toUpdateRecipe
                        });
                    }
                    context.SaveChanges();
                }
                catch (InvalidOperationException e)
                {
                    msg = e.Message + ": no Recipe item exists\n" + "Please, use Refresh button!\n";
                    return(false);
                }
                catch (DbEntityValidationException dbEx)
                {
                    StringBuilder msgB = new StringBuilder();
                    foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors)
                    {
                        foreach (DbValidationError error in entityErr.ValidationErrors)
                        {
                            msgB.Append(error.PropertyName + ": " + error.ErrorMessage + "\n");
                        }
                    }
                    msgB.Append("Please, select or fill the required informations.");
                    msg = msgB.ToString();
                    return(false);
                }
            }

            FillRecipe();
            msg = "Updated a Recipe: " + recipe.Title;
            return(true);
        }
Ejemplo n.º 21
0
        private RecipesController CreateRecipesController()
        {
            var options          = _fixture.Options;
            var recipesContext   = new RecipesContext(options);
            var databaseActions  = new DatabaseActions(recipesContext);
            var ingredientDomain = new IngredientDomain(databaseActions);
            var recipesDomain    = new RecipesDomain(databaseActions, ingredientDomain);

            return(new RecipesController(recipesDomain));
        }
Ejemplo n.º 22
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_recipiesContext != null)
         {
             _recipiesContext.Dispose();
             _recipiesContext = null;
         }
     }
 }
Ejemplo n.º 23
0
        public async Task TestReturnsBadRequestWhenRecipeIdIsUnknown()
        {
            var options        = _fixture.Options;
            var recipesContext = new RecipesContext(options);
            var controller     = CreateRecipesController(recipesContext);
            var ingredientList = new List <UpdatedIngredientDto>();
            var unknownRecipe  = new UpdatedRecipeDto("Updated recipe", "Updated description", ingredientList, 8888);

            var result = await controller.PatchRecipe(9999, unknownRecipe);

            Assert.IsType <BadRequestResult>(result.Result);
        }
Ejemplo n.º 24
0
        public async Task RecipeUpdate_AddingOneImageToRecipeWithImages_IsAddedProperlyAndPathCreated()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 6;
                // Setup context with one recipe, and medias
                SetupBasicContext(options, false, recipeId);

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID defined at class level
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // loading mediaDtos from json (to have media with image bytes)
                    var mediaDtos  = LoadRecipeMediaDtoFromJson(recipeId);
                    var mediaToAdd = mediaDtos.First();
                    recipeToUpdate.Medias.Add(mediaToAdd);

                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    Assert.AreEqual(4, recipeUpdated.Medias.Count);

                    string userRecipePath;
                    // We can't access image path but we can recreate it from method used by service when saving it
                    var savedImgPath = MediaLogicHelper.GenerateSingleMediaPath(this._mediaHelper.UserMediasPath, recipeUpdated.Id, 4, out userRecipePath);
                    // check file exists
                    Assert.IsTrue(File.Exists(savedImgPath));
                    long savedImageSize = new FileInfo(savedImgPath).Length;
                    // verify size is under 800kb
                    Assert.Less(savedImageSize, this.MAX_IMAGESIZE);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 25
0
 // TODO: REMOVE
 public static void EnsureCreated(RecipesContext context)
 {
     if (context.Database.EnsureCreated())
     {
         using var viewCommand   = context.Database.GetDbConnection().CreateCommand();
         viewCommand.CommandText = @"
                 CREATE VIEW AllResources AS
                 SELECT *
                 FROM Recipes;";
         viewCommand.ExecuteNonQuery();
     }
 }
Ejemplo n.º 26
0
        private static void CrawlToDatabase()
        {
            var db             = new RecipesContext();
            var recipesService = new RecipesService(db);

            ICrawler crawler = new AllRecipesCrawler {
                Logger = Log
            };

            // crawler.ProcessRecipes(RecipeIdProvider.Range(6800, 6810), recipesService.Add);
            crawler.ProcessRecipes(RecipeIdProvider.Random(6800, 300000, 20), recipesService.Add);
        }
Ejemplo n.º 27
0
        // Test adding recipe with instructions/ingredients/all props and 1 media
        public async Task RecipeAdd_WithAllProperties_Works()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options); // TODO: move into setup?
                int createdRecipeId = -1;
                using (var context = new RecipesContext(options))
                {
                    var service   = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var newRecipe = new RecipeDto
                    {
                        Description  = "Something",
                        LastModifier = "xx",
                        TitleShort   = "NewRecipe",
                        TitleLong    = "Gorgeous wedding cake",
                        OriginalLink = "https://www.foodnetwork.com/recipes/geoffrey-zakarian/classic-gin-gimlet-2341489",
                        Id           = 5 // should reset to 0 and be assigned by DB
                    };

                    var response = await service.AddOne(newRecipe);

                    Assert.IsTrue(response.Success);
                    var rgx   = new Regex(@"^.*Id:(?<id>[0-9])$");
                    var match = rgx.Match(response.Message);
                    createdRecipeId = Convert.ToInt32(match.Groups["id"].Value);
                }
                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipe  = await service.GetOne(createdRecipeId);

                    Assert.AreEqual("Something", recipe.Description);
                    Assert.AreEqual("xx", recipe.LastModifier);
                    Assert.AreEqual("NewRecipe", recipe.TitleShort);
                    Assert.AreEqual("Gorgeous wedding cake", recipe.TitleLong);
                    Assert.AreEqual("https://www.foodnetwork.com/recipes/geoffrey-zakarian/classic-gin-gimlet-2341489", recipe.OriginalLink);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 28
0
        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            Recipe          recipe    = new Recipe();
            AddRecipeDialog addDialog = new AddRecipeDialog();

            if (recipeListBox.SelectedItem != null)
            {
                recipe = (Recipe)recipeListBox.SelectedItem;
                addDialog.titleTextBox.Text               = recipe.Title;
                addDialog.yeildTextBox.Text               = recipe.Yield;
                addDialog.directionTextBox.Text           = recipe.Directions;
                addDialog.servingSizeTextBox.Text         = recipe.ServingSize;
                addDialog.recipeTypeListBox.SelectedValue = recipe.RecipeType;
                addDialog.commentTextBox.Text             = recipe.Comment;

                bool save = (bool)addDialog.ShowDialog();

                if (save)
                {
                    using (RecipesContext context = new RecipesContext())
                    {
                        //var query = from title in context.Recipes where title.RecipeID == recipe.RecipeID select title;

                        //foreach (Recipe r in query)
                        //{

                        recipe.Title       = addDialog.titleTextBox.Text;
                        recipe.Yield       = addDialog.yeildTextBox.Text;
                        recipe.Directions  = addDialog.directionTextBox.Text;
                        recipe.ServingSize = addDialog.servingSizeTextBox.Text;
                        recipe.RecipeType  = addDialog.recipeTypeListBox.SelectedValue.ToString();
                        recipe.Comment     = addDialog.commentTextBox.Text;
                        //}
                        try
                        {
                            context.Recipes.Add(recipe);
                            context.SaveChanges();
                            btnRefresh.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Button.ClickEvent));
                        }
                        catch
                        {
                            errorLabel.Content = "$Failed to copy {addDialog.titleTextBox.Text}";
                        }
                    }
                    addDialog.Close();
                }
                else
                {
                    errorLabel.Content = "You must select a recipe before clicking Modify";
                }
            }
        }
Ejemplo n.º 29
0
        public async Task RecipeUpdate_UpdatingRecipeAndIngredient_IsUpdated()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options);

                using (var context = new RecipesContext(options))
                {
                    var service        = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipeToUpdate = await service.GetOne(4);

                    // modifying recipe properties
                    recipeToUpdate.OriginalLink = "https://www.something.com";
                    recipeToUpdate.TitleShort   = "Banana pancakes";

                    // modifying ingredient with id 1
                    var ingredient = recipeToUpdate.Ingredients.FirstOrDefault(i => i.Id == 1);
                    // overriding ingredient to remove linked/tracked objects, and modifying some properties
                    recipeToUpdate.Ingredients.Remove(ingredient);
                    recipeToUpdate.Ingredients.Add(new IngredientBase {
                        Id = ingredient.Id, Name = "Strawberry", Quantity = 1, Unit_Id = 3, Recipe_Id = ingredient.Recipe_Id
                    });

                    await service.UpdateOne(recipeToUpdate);

                    // get recipe again
                    var newRecipe = await service.GetOne(4);

                    Assert.AreEqual("Banana pancakes", newRecipe.TitleShort);
                    Assert.AreEqual("https://www.something.com", newRecipe.OriginalLink);

                    ingredient = recipeToUpdate.Ingredients.FirstOrDefault(i => i.Id == 1);
                    Assert.AreEqual("Strawberry", ingredient.Name);
                    Assert.AreEqual(1, ingredient.Quantity);
                    Assert.AreEqual(3, ingredient.Unit_Id);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 30
0
        public async Task TestReturnsNotFoundWhenRecipeIdIsNotFound()
        {
            var options        = _fixture.Options;
            var recipesContext = new RecipesContext(options);
            var controller     = CreateRecipesController(recipesContext);
            var ingredientList = new List <UpdatedIngredientDto>();
            var newRecipe      = new UpdatedRecipeDto("Updated recipe", "Updated description", ingredientList, 9999);

            var result = await controller.PatchRecipe(9999, newRecipe);

            var error = result.Result;

            Assert.IsType <NotFoundResult>(error);
        }
Ejemplo n.º 31
0
        public void SetUserPrincipal(string authorization)
        {
            User user;

            using (var context = new RecipesContext()){
                var userRepo = new UserRepository(context);
                user = userRepo.GetUserByAccessToken(authorization);
            }

            UserIdentity identity = null;

            if (user != null && user.AccessTokenExpiry > DateTime.UtcNow)
            {
                identity = new UserIdentity(user);
            }

            if (identity != null)
            {
                SetPrincipal(new UserPrincipal(identity));
            }
        }