public RecipeImageTransfer(RecipeImage recipeImage) { if (!string.IsNullOrWhiteSpace(recipeImage.FilePath)) { imageBytes = File.ReadAllBytes(recipeImage.FilePath); } }
void ReleaseDesignerOutlets() { if (frameView != null) { frameView.Dispose(); frameView = null; } if (RecipeCookTime != null) { RecipeCookTime.Dispose(); RecipeCookTime = null; } if (RecipeImage != null) { RecipeImage.Dispose(); RecipeImage = null; } if (RecipeName != null) { RecipeName.Dispose(); RecipeName = null; } }
public async Task <JsonResult> UploadRecipeImage() { var files = Request.Form.Files; int recipeId = Request.Form.FirstOrDefault(x => x.Key == "recipeId").Value.ToString().ToInt(); foreach (var file in files) { using var ms = new MemoryStream(); file.CopyTo(ms); var fileBytes = ms.ToArray(); var recipeImage = new RecipeImage() { RecipeId = recipeId, FileName = file.FileName, FileSize = file.Length, ContentType = file.ContentType, ContentValue = Convert.ToBase64String(fileBytes) }; if (!await recipeImageRepository.InsertRecipeImage(recipeImage)) { return(new JsonResult(new { result = false, message = "Ζητάμε συγνώμη δεν μπορέσαμε να αποθηκεύσουμε τις φωτογραφίες σας." })); } } return(new JsonResult(new { result = true })); }
public async Task <IActionResult> IndexImage() { var client = new HttpClient(); var response = await client.GetAsync(_baseUrl); if (response.IsSuccessStatusCode) { var recipes = JsonConvert.DeserializeObject <List <Recipe> >(await response.Content.ReadAsStringAsync()); var images = JsonConvert.DeserializeObject <List <Image> >(await(await client.GetAsync("http://localhost:50541/api/Images")).Content.ReadAsStringAsync()); var listRecImg = new List <RecipeImage>(); foreach (var recipe in recipes) { var image = images.Where(x => x.RecipeId == recipe.Id).ToList().First(); RecipeImage recipeImage = new RecipeImage { Recipe = recipe, Image = image }; listRecImg.Add(recipeImage); } return(View(listRecImg)); } return(NotFound()); }
/// <summary> /// Creates a new entity in the Database /// </summary> /// <param name="recipeId">Id of the owning recipe</param> /// <param name="creationModel">entity data</param> /// <returns></returns> public async Task <RecipeImageViewModel> AddAsync(int recipeId, IFormFile creationModel) { RecipeImageViewModel result; try { var url = await this.ImageService.UploadImageAsync(recipeId, creationModel); var datamodel = new RecipeImage() { RecipeId = recipeId, Filename = creationModel.FileName, Url = url }; await Repository.AddAsync(datamodel); result = this.Mapper.Map <RecipeImageViewModel>(datamodel); Logger.LogDebug($"New recipe image '{datamodel.Id}' successfully created"); } catch (Exception e) { Logger.LogError(new EventId(), e, $"An Error occured while creating a recipe image"); throw new Exception($"An Error occured while creating a recipe image"); } return(result); }
static public HtmlString ConvertImageToHtml(this IHtmlHelper htmlHelper, RecipeImage image) { if (image is null) { return(new HtmlString("")); } return(new HtmlString($"data:{image.ContentType};charset=utf-8;base64,{image.ContentValue}")); }
public async Task <bool> UpdateRecipeImage(RecipeImage recipeImage) { context.SC_RecipeImage.Update(recipeImage); if (await context.SaveChangesAsync() <= 0) { return(false); } return(true); }
private async void deleteImage(object sender, RoutedEventArgs e) { RecipeImage imageToRemove = (RecipeImage)((MenuFlyoutItem)e.OriginalSource).DataContext; bool result = await tryDeleteItem("image"); if (result) { images.Remove(imageToRemove); if (imageToRemove.ID > 0) { removedImages.Add(imageToRemove); } } }
public async Task <IActionResult> UploadRecipe([FromForm] RecipeImage recipe) { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } try { using (var stream = recipe.Image.OpenReadStream()) { var cloudBlock = await UploadToBlob(recipe.Image.FileName, null, stream); //// Retrieve the filename of the file you have uploaded //var filename = provider.FileData.FirstOrDefault()?.LocalFileName; if (string.IsNullOrEmpty(cloudBlock.StorageUri.ToString())) { return(BadRequest("An error has occured while uploading your file. Please try again.")); } Recipe recipeItem = new Recipe(); recipeItem.Name = recipe.Name; recipeItem.Tags = recipe.Tags; recipeItem.Author = recipe.Author; recipeItem.Overview = recipe.Overview; recipeItem.Ingridients = recipe.Ingridients; recipeItem.Description = recipe.Description; System.Drawing.Image image = System.Drawing.Image.FromStream(stream); recipeItem.Height = image.Height.ToString(); recipeItem.Width = image.Width.ToString(); recipeItem.Url = cloudBlock.SnapshotQualifiedUri.AbsoluteUri; recipeItem.Uploaded = DateTime.Now.ToString(); // public string Overview { get; set; } //public string Ingridients { get; set; } //public string Description { get; set; } _context.Recipe.Add(recipeItem); await _context.SaveChangesAsync(); return(Ok($"File: {recipe.Name} has successfully uploaded")); } } catch (Exception ex) { return(BadRequest($"An error has occured. Details: {ex.Message}")); } }
public async Task TestUploadFileFail() { using (var context = new MyRecipesContext(options)) { RecipeImage image = new RecipeImage(); try { RecipesController recipeController = new RecipesController(context, configuration); IActionResult okResult = await recipeController.UploadRecipe(image) as IActionResult; } catch (Exception e) { // Assert Assert.IsInstanceOfType(e, typeof(ArgumentException)); } } }
/// <summary> /// Deletes the given image from the database /// </summary> /// <param name="deletingImage"> /// the image to delete /// </param> public static void deleteImage(RecipeImage deletingImage) { SqliteConnection db = new SqliteConnection("Filename=RecipeBook.db"); db.Open(); SqliteCommand deleteCommand = new SqliteCommand(); deleteCommand.Connection = db; deleteCommand.CommandText = "DELETE FROM IMAGES WHERE ID = @ID"; deleteCommand.Parameters.AddWithValue("@ID", deletingImage.ID); deleteCommand.ExecuteNonQuery(); db.Close(); }
protected List <RecipeImage> getRecipeImages(HtmlNode node) { var pageNodes = getRecipeImagesPageNodes(node); List <RecipeImage> images = new List <RecipeImage>(); foreach (var pageNode in pageNodes) { List <string> imageURLs = new List <string>(); var imageNodes = pageNode.SelectNodes(imagesXPath); if (imageNodes == null) { imageNodes = pageNode.SelectNodes(images2XPath); } if (imageNodes == null) { continue; } foreach (var imgNode in imageNodes) { var imageURL = getImageURL(imgNode); if (imageURL == null) { continue; } if (!imageURL.StartsWith(baseURL) && !imageURL.StartsWith("http://") && !imageURL.StartsWith("https://") && !imageURL.StartsWith("//")) { imageURL = baseURL + imageURL; } if (imageURLs.Contains(imageURL)) { continue; } imageURLs.Add(imageURL); RecipeImage img = new RecipeImage(); img.ImageURL = imageURL; img.LocalImagePath = null; images.Add(img); } } return(images); }
/* * Save the changes made to an existing recipe or add the new * recipe to the recipe list. */ private async void saveRecipe(object sender, RoutedEventArgs e) { String newRecipeName = this.recipeName.Text; // double newRecipeRating = this.recipeRating.Value; recipe.Name = newRecipeName; // recipe.Rating = newRecipeRating; recipe.setImages(images); recipe.setIngredients(ingredients); recipe.setSteps(steps); if (!recipes.isEditing()) { recipes.addRecipe(recipe); recipes.SelectedIndex = recipes.getRecipeList().Count - 1; } else { recipes.setEditing(false); RecipeBookDataAccessor.updateRecipe(recipe); } for (int i = 0; i < removedSteps.Count; i++) { RecipeBookDataAccessor.deleteStep(removedSteps[i]); } for (int i = 0; i < removedIngredients.Count; i++) { RecipeBookDataAccessor.deleteIngredient(removedIngredients[i]); } for (int i = 0; i < removedImages.Count; i++) { RecipeImage imageToRemove = removedImages[i]; StorageFile imageFile = await StorageFile.GetFileFromPathAsync(imageToRemove.getImagePath()); await imageFile.DeleteAsync(); RecipeBookDataAccessor.deleteImage(imageToRemove); } Frame.GoBack(); }
/* * Add a new image to the recipe's image list. The image is * selected by teh user from a file dialog. */ private async void addImage(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile imageFile = await picker.PickSingleFileAsync(); if (imageFile != null) { StorageFile tempImage = await imageFile.CopyAsync(tempImageFolder); Uri imageUri = new Uri(tempImage.Path, UriKind.Absolute); RecipeImage newImage = null; BitmapImage addedImage = null; if (tempImage.IsAvailable) { using (IRandomAccessStream stream = await tempImage.OpenAsync(FileAccessMode.Read)) { addedImage = new BitmapImage(); await addedImage.SetSourceAsync(stream); newImage = new RecipeImage(addedImage); stream.Dispose(); } } else { addedImage = new BitmapImage(); addedImage.UriSource = imageUri; newImage = new RecipeImage(addedImage); } newImage.ImagePath = imageUri.AbsoluteUri; images.Add(newImage); this.imageFlipView.SelectedIndex = this.images.Count - 1; } }
/// <summary> /// Adds the given recipe image to the database. /// </summary> /// <param name="newImage"> /// the new image to add /// </param> public static void addImage(RecipeImage newImage) { SqliteConnection db = new SqliteConnection("Filename=RecipeBook.db"); db.Open(); SqliteCommand insertCommand = new SqliteCommand(); insertCommand.Connection = db; insertCommand.CommandText = "INSERT INTO IMAGES " + "(ID, PATH, RID) VALUES " + "(@ID, @Path, @RecipeID)"; insertCommand.Parameters.AddWithValue("@ID", newImage.ID); insertCommand.Parameters.AddWithValue("@Path", newImage.ImagePath); insertCommand.Parameters.AddWithValue("@RecipeID", newImage.RecipeID); insertCommand.ExecuteReader(); db.Close(); }
public async Task <IActionResult> GetFaveRecipes(string userId) { var client = new HttpClient(); var response = await client.GetAsync(_baseUrl); if (response.IsSuccessStatusCode) { var faveRecipesAll = JsonConvert.DeserializeObject <List <FavouriteRecipe> >(await response.Content.ReadAsStringAsync()); var images = JsonConvert.DeserializeObject <List <Image> >(await(await client.GetAsync("http://localhost:50541/api/Images")).Content.ReadAsStringAsync()); var faveRecipesForUser = faveRecipesAll.Where(x => x.AppUserId.Equals(userId)).ToList(); var listRecImg = new List <RecipeImage>(); if (faveRecipesForUser.Count == 0) { return(RedirectToAction("FavouriteRecipeNotFound")); } else { foreach (var faveRecipe in faveRecipesForUser) { var recipe = _context.Recipes.FirstOrDefault(x => x.Id == faveRecipe.RecipeId); var image = images.FirstOrDefault(x => x.RecipeId == faveRecipe.RecipeId); RecipeImage recipeImage = new RecipeImage { Recipe = recipe, Image = image }; listRecImg.Add(recipeImage); } } return(View(listRecImg)); } return(NotFound()); }
private List <RecipeImage> HttpFileToRecipeImage(IEnumerable <HttpPostedFileBase> files) { List <RecipeImage> filesDataResult = new List <RecipeImage>(); foreach (var file in files) { if (file == null) { continue; } RecipeImage image = new RecipeImage(); image.OriginalName = file.FileName; image.Extension = Path.GetExtension(file.FileName); MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); image.Content = target.ToArray(); filesDataResult.Add(image); } return(filesDataResult); }
/// <summary> /// Gets a list of all the images that are associated to the /// given recipe ID. /// </summary> /// <param name="recipeId"> /// the ID of the recipe for which images will be retrieved. /// </param> /// <returns> /// an observable collection of images associated to the given /// recipe. /// </returns> public static ObservableCollection <RecipeImage> getImages(long recipeId) { ObservableCollection <RecipeImage> savedImages = new ObservableCollection <RecipeImage>(); SqliteConnection db = new SqliteConnection("Filename=RecipeBook.db"); db.Open(); SqliteCommand selectCommand = new SqliteCommand("SELECT * from IMAGES WHERE RID = " + recipeId, db); SqliteDataReader query = selectCommand.ExecuteReader(); while (query.Read()) { long id = query.GetInt64(0); String path = query.GetString(1); long rid = query.GetInt64(2); RecipeImage savedImage = new RecipeImage(id, path); savedImage.RecipeID = rid; savedImages.Add(savedImage); } db.Close(); return(savedImages); }
public void Convert_RecipeImage_To_RecipeImageViewModel() { Initialize(); var recipe = new Recipe() { Name = "MyRecipe", Id = 1 }; var input = new RecipeImage() { Recipe = recipe, Id = 1, RecipeId = recipe.Id, Url = "http://www.service/images/1", Filename = "MyImage.jpg" }; var output = Mapper.Map <RecipeImageViewModel>(input); Assert.Equal(input.Id, output.Id); Assert.Equal(input.Filename, output.Filename); Assert.Equal(input.Url, output.Url); }
private List<RecipeImage> HttpFileToRecipeImage(IEnumerable<HttpPostedFileBase> files) { List<RecipeImage> filesDataResult = new List<RecipeImage>(); foreach (var file in files) { if (file == null) { continue; } RecipeImage image = new RecipeImage(); image.OriginalName = file.FileName; image.Extension = Path.GetExtension(file.FileName); MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); image.Content = target.ToArray(); filesDataResult.Add(image); } return filesDataResult; }
private async void Share() { if (string.IsNullOrEmpty(this.TextRecipeName)) { BCRecipeName = ColorsFonts.errorColor; await Application.Current.MainPage.DisplayAlert("Error", "You must enter the recipe name", "Ok"); return; } if (string.IsNullOrEmpty(this.TextIngredients)) { BCIngredients = ColorsFonts.errorColor; await Application.Current.MainPage.DisplayAlert("Error", "You must enter the ingredients", "Ok"); return; } if (string.IsNullOrEmpty(this.TextInstructions)) { BCInstructions = ColorsFonts.errorColor; await Application.Current.MainPage.DisplayAlert("Error", "You must enter the instructions", "Ok"); return; } if (string.IsNullOrEmpty(this.TextTags)) { BCTags = ColorsFonts.errorColor; await Application.Current.MainPage.DisplayAlert("Error", "You must enter some tags", "Ok"); return; } if (string.IsNullOrEmpty(this.TextPrice)) { BCPrice = ColorsFonts.errorColor; await Application.Current.MainPage.DisplayAlert("Error", "You must enter the price", "Ok"); return; } var checkConnection = await ApiService.CheckConnection(); //Checks the internet connection before interacting with the server if (!checkConnection.IsSuccess) { await Application.Current.MainPage.DisplayAlert( "Error", "Check your internet connection", "Accept"); return; } //Changes the spacing on every string that is being uploaded this.TextRecipeName = ReadStringConverter.ChangePostString(this.TextRecipeName); this.preparationTime = $"{this.DurationHourValue} h and {this.DurationMinutesValue} min"; this.preparationTime = ReadStringConverter.ChangePostString(this.preparationTime); this.TextDishTime = ReadStringConverter.ChangePostString(this.TextDishTime); this.TextIngredients = ReadStringConverter.ChangePostString(this.TextIngredients); this.TextInstructions = ReadStringConverter.ChangePostString(this.TextInstructions); this.TextTags = ReadStringConverter.ChangePostString(this.TextTags); var recipe = new Recipe { Name = this.TextRecipeName, Author = this.loggedUser.Email, Type = this.TextDishType, CookingSpan = this.preparationTime, Portions = this.PortionsValue, EatingTime = this.TextDishTime, Tags = this.TextTags, Ingredients = this.TextIngredients, Steps = this.TextInstructions, Price = this.TextPrice, Difficulty = this.DifficultyValue, Punctuation = 0 }; //Generates the query url var queryUrl = "/recipes?name=" + this.TextRecipeName + "&author=" + this.loggedUser.Email + "&type=" + this.TextDishType + "&cookingSpan=" + this.preparationTime + "&portions=" + this.PortionsValue + "&eatingTime=" + this.TextDishTime + "&tags=" + this.TextTags + "&ingredients=" + this.TextIngredients + "&steps=" + this.TextInstructions + "&price=" + this.TextPrice + "&difficulty=" + this.DifficultyValue + "&punctuation=0"; //Posts the recipe var response = await ApiService.Post <Recipe>( "http://localhost:8080/CookTime.BackEnd", "/api", queryUrl, recipe, false); if (!response.IsSuccess) { await Application.Current.MainPage.DisplayAlert( "Error", response.Message, "Accept"); return; } if (this.imageByteArray != null) { string arrayConverted = Convert.ToBase64String(this.imageByteArray); this.imageByteArray = null; var recipeImage = new RecipeImage { RecipeName = this.TextRecipeName, Image = arrayConverted }; var responseImage = await ApiService.Put <RecipeImage>( "http://localhost:8080/CookTime.BackEnd", "/api", "/recipes/image", recipeImage, false); if (!responseImage.IsSuccess) { await Application.Current.MainPage.DisplayAlert( "Error", responseImage.Message, "Accept"); return; } } // Redifines the addRecipe entries and editors this.TextRecipeName = string.Empty; this.DurationHourValue = 0; this.DurationMinutesValue = 10; this.TextDishType = "Breakfast"; this.PortionsValue = 1; this.TextDishTime = "Appetizer"; this.TextIngredients = string.Empty; this.TextInstructions = string.Empty; this.TextTags = string.Empty; this.TextPrice = string.Empty; this.DifficultyValue = 3; this.AddImageSource = "AddImageIcon"; await Application.Current.MainPage.DisplayAlert("New Recipe!", "Recipe succesfully posted", "Ok"); }
public async Task EditAsync(RecipeEditViewModel viewModel, string rootPath) { var recipe = this.recipesRepository.All() .FirstOrDefault(x => x.Id == viewModel.Id); if (recipe == null) { throw new NullReferenceException(string.Format(ExceptionMessages.RecipeMissing, viewModel.Id)); } if (this.recipesRepository.All().Any(x => x.Name == viewModel.Name && x.Id != viewModel.Id)) { throw new ArgumentException(ExceptionMessages.RecipeAlreadyExists, viewModel.Name); } recipe.Name = viewModel.Name; recipe.PreparationTime = TimeSpan.FromMinutes(viewModel.PreparationTime); recipe.CookingTime = TimeSpan.FromMinutes(viewModel.CookingTime); recipe.Portions = viewModel.Portions; recipe.Preparation = viewModel.Preparation; recipe.Notes = viewModel.Notes; recipe.ModifiedOn = DateTime.UtcNow; var cookingVesselBeforeEdit = this.cookingVesselRepository.All() .FirstOrDefault(x => x.Id == recipe.CookingVesselId); if (cookingVesselBeforeEdit.Id != viewModel.CookingVesselId) { var cookingVessel = this.cookingVesselRepository.All() .FirstOrDefault(x => x.Id == viewModel.CookingVesselId); if (cookingVessel == null) { throw new NullReferenceException( string.Format(ExceptionMessages.CookingVesselMissing, viewModel.CookingVesselId)); } recipe.CookingVesselId = viewModel.CookingVesselId; cookingVessel.Recipes.Add(recipe); cookingVesselBeforeEdit.Recipes.Remove(recipe); } var recipesCategoriesBeforeEdit = await this.categoryRecipesRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var recipesCategory in recipesCategoriesBeforeEdit) { this.categoryRecipesRepository.HardDelete(recipesCategory); } await this.categoryRecipesRepository.SaveChangesAsync(); foreach (var categoryId in viewModel.CategoriesCategoryId) { var category = this.categoryRepository.All() .FirstOrDefault(x => x.Id == categoryId); if (category == null) { throw new NullReferenceException(string.Format(ExceptionMessages.CategoryMissing, categoryId)); } var categoryRecipe = new CategoryRecipe { CategoryId = categoryId, RecipeId = recipe.Id, }; recipe.Categories.Add(categoryRecipe); category.Recipes.Add(categoryRecipe); } var recipeIngredientsBeforeEdit = await this.ingredientRecipeRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var recipeIngredient in recipeIngredientsBeforeEdit) { this.ingredientRecipeRepository.HardDelete(recipeIngredient); } await this.ingredientRecipeRepository.SaveChangesAsync(); foreach (var recipeIngredient in viewModel.Ingredients) { var ingredient = this.ingredientRepository.All() .FirstOrDefault(x => x.Id == recipeIngredient.IngredientId); if (ingredient == null) { throw new NullReferenceException( string.Format(ExceptionMessages.IngredientMissing, recipeIngredient.IngredientId)); } var ingredientRecipe = new RecipeIngredient { IngredientId = recipeIngredient.IngredientId, WeightInGrams = recipeIngredient.WeightInGrams, PartOfRecipe = recipeIngredient.PartOfRecipe, RecipeId = recipe.Id, }; recipe.Ingredients.Add(ingredientRecipe); ingredient.Recipies.Add(ingredientRecipe); } if (viewModel.ImagesToSelect != null) { var imagesBeforeEdit = await this.recipeImageRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var image in imagesBeforeEdit) { this.recipeImageRepository.HardDelete(image); } await this.recipeImageRepository.SaveChangesAsync(); foreach (var fileImage in viewModel.ImagesToSelect) { var image = new RecipeImage(); image.ImageUrl = $"/assets/img/recipes/{image.Id}.jpg"; image.RecipeId = recipe.Id; string imagePath = rootPath + image.ImageUrl; using (FileStream stream = new FileStream(imagePath, FileMode.Create)) { await fileImage.CopyToAsync(stream); } recipe.Images.Add(image); } await this.recipeImageRepository.SaveChangesAsync(); } this.recipesRepository.Update(recipe); await this.recipesRepository.SaveChangesAsync(); await this.cookingVesselRepository.SaveChangesAsync(); await this.categoryRecipesRepository.SaveChangesAsync(); await this.categoryRepository.SaveChangesAsync(); await this.ingredientRecipeRepository.SaveChangesAsync(); await this.ingredientRepository.SaveChangesAsync(); var nutrition = this.nutritionRepository.All() .FirstOrDefault(x => x.RecipeId == recipe.Id); if (nutrition != null) { this.nutritionRepository.HardDelete(nutrition); } await this.nutritionsService.CalculateNutritionForRecipeAsync(recipe.Id); }
public async Task <string> CreateAsync(string userId, RecipeInputModel inputModel, string rootPath) { if (this.recipesRepository.All().Any(x => x.Name == inputModel.Name)) { throw new ArgumentException(ExceptionMessages.RecipeAlreadyExists, inputModel.Name); } var cookingVessel = this.cookingVesselRepository.All() .FirstOrDefault(x => x.Id == inputModel.CookingVesselId); if (cookingVessel == null) { throw new NullReferenceException( string.Format(ExceptionMessages.CookingVesselMissing, inputModel.CookingVesselId)); } var recipe = new Recipe { Name = inputModel.Name, PreparationTime = TimeSpan.FromMinutes(inputModel.PreparationTime), CookingTime = TimeSpan.FromMinutes(inputModel.CookingTime), Preparation = inputModel.Preparation, Notes = inputModel.Notes, Portions = inputModel.Portions, CreatorId = userId, CookingVesselId = inputModel.CookingVesselId, }; cookingVessel.Recipes.Add(recipe); var user = this.userRepository.All() .FirstOrDefault(x => x.Id == userId); user.CreatedRecipes.Add(recipe); foreach (var imageFile in inputModel.Images) { var image = new RecipeImage(); image.ImageUrl = $"/assets/img/recipes/{image.Id}.jpg"; image.RecipeId = recipe.Id; string imagePath = rootPath + image.ImageUrl; using (FileStream stream = new FileStream(imagePath, FileMode.Create)) { await imageFile.CopyToAsync(stream); } recipe.Images.Add(image); } foreach (var categoryId in inputModel.SelectedCategories) { var category = this.categoryRepository.All() .FirstOrDefault(x => x.Id == categoryId); if (category == null) { throw new NullReferenceException( string.Format(ExceptionMessages.CategoryMissing, categoryId)); } var categoryRecipe = new CategoryRecipe { CategoryId = categoryId, RecipeId = recipe.Id, }; recipe.Categories.Add(categoryRecipe); category.Recipes.Add(categoryRecipe); } foreach (var ingredientInputModel in inputModel.SelectedIngredients) { var ingredient = this.ingredientRepository.All() .FirstOrDefault(x => x.Id == ingredientInputModel.IngredientId); if (ingredient == null) { throw new NullReferenceException( string.Format(ExceptionMessages.IngredientMissing, ingredientInputModel.IngredientId)); } var ingredientRecipe = new RecipeIngredient { IngredientId = ingredientInputModel.IngredientId, WeightInGrams = ingredientInputModel.WeightInGrams, PartOfRecipe = ingredientInputModel.PartOfRecipe, RecipeId = recipe.Id, }; recipe.Ingredients.Add(ingredientRecipe); ingredient.Recipies.Add(ingredientRecipe); } await this.recipesRepository.AddAsync(recipe); await this.recipesRepository.SaveChangesAsync(); await this.recipeImageRepository.SaveChangesAsync(); await this.categoryRecipesRepository.SaveChangesAsync(); await this.ingredientRecipeRepository.SaveChangesAsync(); var recipeWithNutrition = this.recipesRepository.All() .Where(x => x.Name == inputModel.Name) .FirstOrDefault(); var recipeIngredients = await this.ingredientRecipeRepository.All() .Where(x => x.RecipeId == recipeWithNutrition.Id) .ToListAsync(); if (recipeWithNutrition.Ingredients.Count > 0) { var nutritions = this.nutritionRepository.All() .ToList() .Where(x => recipeIngredients.Any(y => y.IngredientId == x.IngredientId)) .ToList(); if (nutritions.All(x => x != null) && nutritions.Count() > 0) { await this.nutritionsService.CalculateNutritionForRecipeAsync(recipeWithNutrition.Id); } else { recipeWithNutrition.Nutrition = null; } } return(recipeWithNutrition.Id); }
public RecipeTestData() { #region Init Recipe // ------------------- Generel ---------------------- Recipe = new Recipe() { Name = "My Recipe", Id = 1, Calories = 1, CookedCounter = 2, Creator = "Tester", LastTimeCooked = new DateTime(), NumberOfServings = 3 }; // ------------------- Images ---------------------- var image = new RecipeImage() { Recipe = this.Recipe, Id = 1, RecipeId = Recipe.Id, Url = "http://imageUrl.de", Filename = "MyImage.jpg" }; Recipe.Images.Add(image); // ------------------- Steps ---------------------- var steps = new List <RecipeStep>() { new RecipeStep() { Recipe = Recipe, Id = 1, RecipeId = Recipe.Id, Order = 0, Description = "Step 1" }, new RecipeStep() { Recipe = Recipe, Id = 2, RecipeId = Recipe.Id, Order = 1, Description = "Step 2" } }; Recipe.Steps.AddRange(steps); // ------------------- Tags ---------------------- var tags = new List <RecipeTag>() { new RecipeTag() { Id = 1, Name = "Tag 1" }, new RecipeTag() { Id = 2, Name = "Tag 2" }, }; var recipeTags = new List <RecipeRecipeTag>() { new RecipeRecipeTag() { Recipe = Recipe, RecipeId = Recipe.Id, RecipeTag = tags.First(), RecipeTagId = tags.First().Id }, new RecipeRecipeTag() { Recipe = Recipe, RecipeId = Recipe.Id, RecipeTag = tags.Last(), RecipeTagId = tags.Last().Id }, }; tags.First().Recipes.Add(recipeTags.First()); tags.Last().Recipes.Add(recipeTags.Last()); Recipe.Tags.AddRange(recipeTags); // ------------------- Source ---------------------- var source = new RecipeUrlSource() { Id = 1, Name = "WebSource", Url = "http://www.websource.de" }; var recipeSource = new RecipeSourceRecipe() { Page = 0, Recipe = Recipe, RecipeId = Recipe.Id, Source = source, SourceId = source.Id }; source.RecipeSourceRecipes.Add(recipeSource); Recipe.Source = recipeSource; Recipe.SourceId = source.Id; // ------------------- Ingrediant ---------------------- var ingrediant = new Ingrediant() { Id = 1, Name = "Ingrediant 1" }; var recipeIngrediant = new RecipeIngrediant() { Recipe = Recipe, RecipeId = Recipe.Id, Ingrediant = ingrediant, IngrediantId = ingrediant.Id, Amount = 1, CookingUnit = CookingUnit.Gramm }; ingrediant.Recipes.Add(recipeIngrediant); Recipe.Ingrediants.Add(recipeIngrediant); #endregion UpdateModel = new RecipeUpdateViewModel() { Id = 1, Name = "Old Recipe", Url = "http://www.webservice.de/recipes/1", Calories = Recipe.Calories.GetValueOrDefault(), NumberOfServings = Recipe.NumberOfServings }; CreationModel = new RecipeCreationViewModel() { Name = UpdateModel.Name, Calories = UpdateModel.Calories, NumberOfServings = UpdateModel.NumberOfServings, Creator = Recipe.Creator }; }
private void InitLocalTestData() { //-------------------- Recipes --------------------------------------- var recipe1 = new Recipe() { Id = 0, Name = "Recipe 1", Calories = 1, CookedCounter = 0, Creator = "Tester", LastTimeCooked = new DateTime(), NumberOfServings = 1 }; var recipe2 = new Recipe() { Id = 0, Name = "Recipe 2", Calories = 1, CookedCounter = 0, Creator = "Tester", LastTimeCooked = new DateTime(), NumberOfServings = 1 }; this.Recipes.Add(recipe1); this.Recipes.Add(recipe2); //-------------------- Sources --------------------------------------- var cookbookSource = new RecipeCookbookSource() { Id = 0, ISBN = "ISBN 978-3-86680-192-9", Name = "Cookbook 1", PublishingCompany = "ABC Corp" }; var webSource = new RecipeUrlSource() { Id = 0, Name = "Chefkoch.de", Url = "http://www.chefkoch.de/recipe/1" }; this.Sources.Add(cookbookSource); this.Sources.Add(webSource); //-------------------- Steps --------------------------------------- var recipe1Step1 = new RecipeStep() { Id = 0, Recipe = recipe1, RecipeId = recipe1.Id, Order = 0, Description = "Desc 1" }; var recipe1Step2 = new RecipeStep() { Id = 0, Recipe = recipe1, RecipeId = recipe1.Id, Order = 1, Description = "Desc 2" }; var recipe2Step1 = new RecipeStep() { Id = 0, Recipe = recipe2, RecipeId = recipe2.Id, Order = 0, Description = "Desc 1" }; var recipe2Step2 = new RecipeStep() { Id = 0, Recipe = recipe2, RecipeId = recipe2.Id, Order = 1, Description = "Desc 2" }; var recipe2Step3 = new RecipeStep() { Id = 0, Recipe = recipe2, RecipeId = recipe2.Id, Order = 2, Description = "Desc 3" }; this.Steps.Add(recipe1Step1); this.Steps.Add(recipe1Step2); this.Steps.Add(recipe2Step1); this.Steps.Add(recipe2Step2); this.Steps.Add(recipe2Step3); recipe1.Steps.Add(recipe1Step1); recipe1.Steps.Add(recipe1Step2); recipe2.Steps.Add(recipe2Step1); recipe2.Steps.Add(recipe2Step2); recipe2.Steps.Add(recipe2Step3); var ingrediant1 = new Ingrediant() { Id = 0, Name = "Ingrediant 1" }; var ingrediant2 = new Ingrediant() { Id = 0, Name = "Ingrediant 2" }; var ingrediant3 = new Ingrediant() { Id = 0, Name = "Ingrediant 3" }; var ingrediant4 = new Ingrediant() { Id = 0, Name = "Ingrediant 4" }; var ingrediant5 = new Ingrediant() { Id = 0, Name = "Ingrediant 5" }; this.Ingrediants.Add(ingrediant1); this.Ingrediants.Add(ingrediant2); this.Ingrediants.Add(ingrediant3); this.Ingrediants.Add(ingrediant4); this.Ingrediants.Add(ingrediant5); //-------------------- Images --------------------------------------- var image1 = new RecipeImage() { Id = 0, Recipe = recipe1, RecipeId = recipe1.Id, Filename = "File1.jpg", Url = "http://www.service.de/images/1" }; var image2 = new RecipeImage() { Id = 0, Recipe = recipe1, RecipeId = recipe1.Id, Filename = "File2.jpg", Url = "http://www.service.de/images/2" }; var image3 = new RecipeImage() { Id = 0, Recipe = recipe2, RecipeId = recipe2.Id, Filename = "File3.jpg", Url = "http://www.service.de/images/3" }; this.Images.Add(image1); this.Images.Add(image2); this.Images.Add(image3); recipe1.Images.Add(image1); recipe1.Images.Add(image2); recipe2.Images.Add(image3); //-------------------- Tags --------------------------------------- var tag1 = new RecipeTag() { Id = 0, Name = "Tag 1" }; var tag2 = new RecipeTag() { Id = 0, Name = "Tag 2" }; var tag3 = new RecipeTag() { Id = 0, Name = "Tag 3" }; var tag4 = new RecipeTag() { Id = 0, Name = "Tag 4" }; this.Tags.Add(tag1); this.Tags.Add(tag2); this.Tags.Add(tag3); this.Tags.Add(tag4); }