public IHttpActionResult PutContact(int id, Contact contact) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != contact.Id) { return(BadRequest()); } db.Entry(contact).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ContactExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IActionResult Delete(int id) { var bartender = context.Bartenders.Find(id); if (bartender == null) { return(NotFound()); } context.Bartenders.Remove(bartender); context.SaveChanges(); return(NoContent()); }
public static RecipeIngredientMeasurement GetIngredient(RecipesContext db, string ingredient, Measurement measurement, double qty) { if (string.IsNullOrEmpty(ingredient)) { throw new NotImplementedException(); } if (ingredient.Length > 255) { ingredient = ingredient.Substring(0, 255); } Ingredient ing = db.Ingredients.FirstOrDefault(i => i.IngredientName == ingredient); if (ing == null) { ing = new Ingredient(); ing.IngredientName = ingredient; db.Ingredients.Add(ing); db.SaveChanges(); } int?measurementID = (measurement == null ? (int?)null : measurement.MeasurementID); var im = db.IngredientMeasurements.FirstOrDefault(x => x.IngredientID == ing.IngredientID && x.MeasurementID == measurementID); if (im == null) { im = new IngredientMeasurement(); im.IngredientID = ing.IngredientID; if (measurement != null) { im.MeasurementID = measurement.MeasurementID; } db.IngredientMeasurements.Add(im); db.SaveChanges(); } var recIngrMeasurement = new RecipeIngredientMeasurement(); recIngrMeasurement.IngredientMeasurementID = im.IngredientMeasurementID; if (qty != 0) { recIngrMeasurement.Quantity = (float)qty; } return(recIngrMeasurement); }
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(); } }
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); }
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); }
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); }
public void Add(User user) { if (user?.Username == null || user.Username.Length < 3) { return; } _db.Add(user); _db.SaveChanges(); }
public IActionResult CreateCocktail([FromBody] Cocktail newCocktail) { IQueryable <Cocktail> queryCocktail = recipesContext.Cocktails.Where(d => d.Name == newCocktail.Name); if (queryCocktail.Count() == 0) { IQueryable <Bartender> query = recipesContext.Bartenders.Where(d => d.Name == newCocktail.Inventor.Name); if (query.Count() != 0) { Bartender bar = query.First(); newCocktail.Inventor = bar; } for (int i = 0; i < newCocktail.Measurements.Count(); i++) { IQueryable <Ingredient> queryIngredient = recipesContext.Ingredients.Where(d => d.Name == newCocktail.Measurements[i].ingredient.Name); if (queryIngredient.Count() != 0) { newCocktail.Measurements[i].ingredient = queryIngredient.First(); } IQueryable <Measurements> queryMeasurements = recipesContext.Measurements.Where(d => d.ingredient.Name == newCocktail.Measurements[i].ingredient.Name).Where(d => d.measurements == newCocktail.Measurements[i].measurements); if (queryMeasurements.Count() != 0) { newCocktail.Measurements[i] = queryMeasurements.First(); } } recipesContext.Cocktails.Add(newCocktail); recipesContext.SaveChanges(); } else { return(NotFound()); } //return ""; //recipesContext.Cocktails.Add(newCocktail); //recipesContext.SaveChanges(); return(Created("", newCocktail)); }
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 IHttpActionResult PutRecipes(int id, Recipes recipes) { var userID = User.Identity.GetUserId(); recipes.UserId = userID; recipes.UserId = userID; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != recipes.ID) { return(BadRequest()); } db.Entry(recipes).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!RecipesExists(recipes.ID)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
// TODO: test // - there is NO POINT in testing validation on properties here. Validation is ran at Controller level not Service. private void SetupBasicContext(DbContextOptions <RecipesContext> options) { // Create the schema in the database using (var context = new RecipesContext(options)) { // RecipeServiceTestsHelper.EnsureCreated(context); //} //// Run the test against one instance of the context //using (var context = new RecipesContext(options)) //{ context.Database.EnsureDeleted(); context.Database.EnsureCreated(); // Adding 2 units context.Units.Add(new Unit() { Id = 1, Name = "Cup", Symbol = "Cl" }); context.Units.Add(new Unit() { Id = 3, Name = "Gram", Symbol = "G" }); // Adding a Recipe with 2 instructions context.Recipes.Add(new Recipe() { Id = 4, TitleLong = "LongTitle", TitleShort = "ShortTitle", Description = String.Empty, LastModifier = $"*****@*****.**", OriginalLink = "", AuditDate = null, CreationDate = null, Instructions = new List <Instruction> { new Instruction { StepNum = 1, Description = "Fire up the Oven for 10 min", Recipe_Id = 4 }, new Instruction { StepNum = 2, Description = "Start cutting stuff", Recipe_Id = 4 } } }); context.SaveChanges(); } }
public async Task TestGetRecipes() { // Arrange Recipe recipe1 = new Recipe { Author = "user1", Title = "newtitle", Type = "type1", body = "body1", Ingredients = "Ing1" }; Recipe recipe2 = new Recipe { Author = "user2", Title = "oldtitle", Type = "type2", body = "body2", Ingredients = "Ing2" }; _recipes_context.Add(recipe1); _recipes_context.Add(recipe2); _recipes_context.SaveChanges(); // Act var result = await _recipeController.GetRecipes("old"); var Ok_result = result as OkObjectResult; // Assert Assert.IsNotNull(Ok_result); Assert.IsInstanceOfType(result, typeof(OkObjectResult)); }
// TODO: Tests // - Check for duplicate ingredients? // - Remove everything and add new ones #endregion private void SetupBasicContext(DbContextOptions <RecipesContext> options) { // Create the schema in the database using (var context = new RecipesContext(options)) { RecipeServiceTestsHelper.EnsureCreated(context); } // Run the test against one instance of the context using (var context = new RecipesContext(options)) { // Adding 2 units context.Units.Add(new Unit() { Id = 1, Name = "Cup", Symbol = "Cl" }); context.Units.Add(new Unit() { Id = 3, Name = "Gram", Symbol = "G" }); // Adding a Recipe with 2 ingredients context.Recipes.Add(new Recipe() { Id = 4, TitleLong = "LongTitle", TitleShort = "ShortTitle", Description = String.Empty, LastModifier = $"*****@*****.**", OriginalLink = "", AuditDate = new DateTime(2019, 12, 03), CreationDate = new DateTime(), Ingredients = new List <Ingredient> { new Ingredient { Id = 0, Name = "Chocolate", Quantity = 4, Unit_Id = 1 }, new Ingredient { Id = 0, Name = "Flour", Quantity = 4, Unit_Id = 1 } } }); context.SaveChanges(); } }
private void InitializeRepository() { //creates a temporal test db file using var context = new RecipesContext(DbFileLocation); SeedRootRecipies(context); context.RecipesHistory.Add(new RecipeLogEntry() { VersionID = 11, RecipeID = 10, LastUpdated = DateTime.Now, Title = "Chicken Kyiv version 2", Description = "New Chicken Kyiv description" }); context.RecipesHistory.Add(new RecipeLogEntry() { VersionID = 12, RecipeID = 10, LastUpdated = DateTime.Now, Title = "Chicken Kyiv version 3", Description = "New new Chicken Kyiv description" }); var created = DateTime.Now; context.RecipesTree.Add(new RecipeNode() { RecipeID = 11, AncestryPath = "3/11/", Created = created }); context.RecipesHistory.Add(new RecipeLogEntry() { VersionID = 13, RecipeID = 11, LastUpdated = created, Title = "Baked trout stuffed with beans", Description = "Description of baked trout stuffed with beans" }); context.RecipesHistory.Add(new RecipeLogEntry() { VersionID = 14, RecipeID = 11, LastUpdated = DateTime.Now, Title = "Baked trout stuffed with beans version 2", Description = "new Description of baked trout stuffed with beans" }); context.SaveChanges(); }
public static Measurement GetMeasurement(RecipesContext db, string measurementName, bool create) { if (_measurements == null) { _measurements = db.Measurements.ToList(); } var measurement = _measurements.FirstOrDefault(m => m.MeasurementName.ToLower().Trim() == measurementName.ToLower().Trim()); if (create && measurement == null) { measurement = new Measurement(); measurement.MeasurementName = measurementName; db.Measurements.Add(measurement); db.SaveChanges(); _measurements.Add(measurement); } return(measurement); }
public static RecipeSource GetRecipeSource(RecipesContext db, string sourceName) { if (_recipeSources == null) { lock (_lockRecipeSource) _recipeSources = db.RecipeSources.ToList(); } RecipeSource rs = _recipeSources.FirstOrDefault(x => x.RecipeSourceName == sourceName); if (rs == null) { rs = new RecipeSource(); rs.RecipeSourceName = sourceName; db.RecipeSources.Add(rs); db.SaveChanges(); _recipeSources.Add(rs); } return(rs); }
// TODO: TESTS // TEST that updating Media value that was null works // TEST that updating Media value with null works // Make sure we can't change around how we deal with physical media in MediaLogicHelperTests // Rename the update... image to something normal /// <summary> /// Setup a test set /// </summary> /// <param name="options">The Context Options</param> /// <param name="EmptyMedia">Return recipe if empty images list or with full images list</param> /// <param name="recipeId">Set different recipe Id on each context for test ran in a row</param> private void SetupBasicContext(DbContextOptions <RecipesContext> options, bool EmptyMedia, int recipeId, string testMediaPath = "RecipeUpdate_AllOtherTests") { // Create the schema in the database using (var context = new RecipesContext(options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); // Adding 2 units context.Units.Add(new Unit() { Id = 1, Name = "Cup", Symbol = "Cl" }); context.Units.Add(new Unit() { Id = 3, Name = "Gram", Symbol = "G" }); var medias = new List <Media>(); if (!EmptyMedia) { // Test images are in a non standard path (not <RecipeID>/<MediaID>/image.png) but easier for testing setup var receivedImagesPath = Path.Combine(this._mediasPath, "RecipeServiceMediaTests", testMediaPath); // loading 3 mediaDtos from json medias = new List <Media>() { new Media { Id = 0, Recipe_Id = recipeId, Title = "Tartines", MediaPath = Path.Combine(receivedImagesPath, "tartines.jpg") }, new Media { Id = 0, Recipe_Id = recipeId, Title = "FoodColor", MediaPath = Path.Combine(receivedImagesPath, "foodColor.jpeg") }, new Media { Id = 0, Recipe_Id = recipeId, Title = "OrangeJuice", MediaPath = Path.Combine(receivedImagesPath, "RecipeUpdate_UpdatingExistingMediaImage.jpg") } // using image that we are sure won't be used by other tests }; this._contextMedia = medias; } // Add Ingredients to add extra complexity and make sure we check for errors on attached entities/loops // Example: When Media prop are updated, we attach media that should always be stripped of related entities (like the recipe, which has ingredients, which has units // and introduces a loop bug). This bug will only be seen if we also have ingredients on recipe (because it references another object etc) var ingredients = new List <Ingredient> { new Ingredient { Id = 0, Name = "Chocolate", Quantity = 4, Unit_Id = 1 }, new Ingredient { Id = 0, Name = "Flour", Quantity = 4, Unit_Id = 1 } }; // Adding a Recipe with 2 instructions context.Recipes.Add(new Recipe() { Id = recipeId, TitleLong = "LongTitle", TitleShort = "ShortTitle", Description = String.Empty, LastModifier = $"*****@*****.**", OriginalLink = "", AuditDate = null, CreationDate = null, Medias = medias, Ingredients = ingredients }); context.SaveChanges(); } }
public void Add(Recipe recipe) { _db.Add(recipe); _db.SaveChanges(); }