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); }
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(); } }
// 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?}"); }); }
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); }
// 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); }
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; } }
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); }
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] }); } }
// 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); }
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); }
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); }
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); }
public void XMLRecipesDescendentsShouldMatchDatabaseRows() { RecipesContext context = new RecipesContext(); int dbRecipesRows = context.Recipes.Count(); int xmlRecipesDescendants = RecipesContextInitializer.GetRecipeDataFromXDocument(XMLFileFinder.GetXMLRecipesPath()).Count; Assert.AreEqual(dbRecipesRows, xmlRecipesDescendants); }
static RecipesContext getDbContext() { var context = new RecipesContext(); context.Configuration.AutoDetectChangesEnabled = false; context.Database.CommandTimeout = 120; return(context); }
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)); }
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(); } }
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(); } }
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(); } }
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); }
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)); }
private void Dispose(bool disposing) { if (disposing) { if (_recipiesContext != null) { _recipiesContext.Dispose(); _recipiesContext = null; } } }
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); }
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(); } }
// 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(); } }
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); }
// 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(); } }
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"; } } }
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(); } }
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); }
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)); } }