public RecipeVM(string dbPath, string title, Recipe recipe = null) { _dbPath = dbPath; _createRecipe = new CreateRecipe(this, recipe); _createRecipe.Title = title; _createRecipe.ShowDialog(); }
public async Task <IActionResult> CreateAsync([FromBody] CreateRecipe command) { if (string.IsNullOrEmpty(command.Name.ToString())) { return(BadRequest(new ApiStatus(400, "ItemNameError", "ItemName is null or empty."))); } if (string.IsNullOrEmpty(command.Ingredients.ToString())) { return(BadRequest(new ApiStatus(400, "IngredientsError", "Ingredients are null or empty."))); } if (string.IsNullOrEmpty(command.Description.ToString())) { return(BadRequest(new ApiStatus(400, "DescriptionError", "Recipe description is null or empty."))); } command.Ingredients.ForEach(x => x.Name = x.Name.ToLower()); bool isCreated = await _recipeRepository.CreateAsync( new Recipe( Guid.NewGuid(), command.Name, command.Description, command.Ingredients )); if (isCreated) { return(Ok(new ApiStatus(200, "RecipeCreated", "Recipe created successfully."))); } return(BadRequest(new ApiStatus(400, "RecipesError", "Recipes Bad Request."))); }
public RecipeViewModel(IRecipeDataService recipeDataService) { _recipeDataService = recipeDataService; CreateRecipe = ReactiveCommand.CreateFromTask(ExecuteCreateRecipe); CreateRecipe.Subscribe(x => AddRecipe(x)); Task.Run(Initialize); }
public void Does_Map_Create_Recipe_Work_Correctly() { var dto = new CreateRecipe { Name = "Pizza Hawajska", Calories = 1200, Description = "Smaczna i zdrowa!", MealTypes = new[] { MealType.Snack, MealType.Lunch }, PictureUrl = "https://localhost:5001/img/pizza_hawajska.png", Steps = new[] { "Go into website and order it via phone!", "Wait for pizza boy to come and collect it from him." }, Ingredients = new[] { "1x Phone" } }; var entityId = Guid.Parse("be3dc63e-8f22-4d05-84b1-5fa6f4f652c4"); var expected = new RecipeCreated { EntityId = Guid.Parse("be3dc63e-8f22-4d05-84b1-5fa6f4f652c4"), Name = "Pizza Hawajska", Calories = 1200, Description = "Smaczna i zdrowa!", MealTypes = new[] { MealType.Snack, MealType.Lunch }, PictureUrl = "https://localhost:5001/img/pizza_hawajska.png", Steps = new[] { "Go into website and order it via phone!", "Wait for pizza boy to come and collect it from him." }, Ingredients = new[] { "1x Phone" }, AuthorId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2", Published = new DateTime(2020, 10, 10, 5, 2, 1), Version = 0 }; const string userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2"; var date = new DateTime(2020, 10, 10, 5, 2, 1); var result = _mapper.Map(dto, entityId, date, userId); result.Should().BeEquivalentTo(expected); }
public async Task <ApiResult <GetCreateRecipe> > CreateRecipe(CreateRecipe bundle) { var json = JsonConvert.SerializeObject(bundle); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); var url = $"/api/recipe"; var result = await Create <GetCreateRecipe>(url, httpContent); return(result); }
public async Task <int> CreateAsync(CreateRecipe model, IValidator <CreateRecipe> validator) { ValidateAndThrow(model, validator); var recipe = _mapper.Map <Recipe>(model); var now = DateTime.UtcNow; recipe.Name = recipe.Name.Trim(); if (!string.IsNullOrEmpty(recipe.Description)) { recipe.Description = recipe.Description.Trim(); } foreach (var recipeIngredient in recipe.RecipeIngredients) { recipeIngredient.Ingredient.Name = recipeIngredient.Ingredient.TaskId.HasValue ? null : recipeIngredient.Ingredient.Name.Trim(); if (recipeIngredient.Amount.HasValue) { if (recipeIngredient.Amount.Value == 0) { recipeIngredient.Amount = null; recipeIngredient.Unit = null; } } else { recipeIngredient.Unit = null; } recipeIngredient.CreatedDate = recipeIngredient.ModifiedDate = now; recipeIngredient.Ingredient.CreatedDate = recipeIngredient.Ingredient.ModifiedDate = now; } if (!string.IsNullOrEmpty(recipe.Instructions)) { recipe.Instructions = Regex.Replace(recipe.Instructions, @"(?:\r\n|\r(?!\n)|(?<!\r)\n){2,}", Environment.NewLine + Environment.NewLine).Trim(); } var minute = TimeSpan.FromMinutes(1); recipe.PrepDuration = recipe.PrepDuration < minute ? null : recipe.PrepDuration; recipe.CookDuration = recipe.CookDuration < minute ? null : recipe.CookDuration; recipe.CreatedDate = recipe.ModifiedDate = recipe.LastOpenedDate = now; int id = await _recipesRepository.CreateAsync(recipe); if (model.ImageUri != null) { await _cdnService.RemoveTempTagAsync(model.ImageUri); } return(id); }
public async Task <IActionResult> CreateRecipeAsync(int id, [FromBody] CreateRecipe command) { if (id != AccountID) { return(Forbid()); } var user = await _userService.GetAsync(id); var recipe = await _recipeService.AddAsync(command, user); var recipeDto = _mapper.Map <RecipeDto>(recipe); return(Created($"{Request.Host}{Request.Path}/{recipe.Id}", recipeDto)); }
public async Task <IActionResult> Create([FromBody] CreateRecipe bundle) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _recipeService.Create(bundle); if (!result.IsSuccessed) { return(BadRequest(result)); } return(Ok(result)); }
public virtual RecipeCreated Map(CreateRecipe dto, Guid entityId, DateTime publishTime, string userId) { return(new RecipeCreated { Published = publishTime, EntityId = entityId, AuthorId = userId, Name = dto.Name, Description = dto.Description, PictureUrl = dto.PictureUrl, Calories = dto.Calories, Steps = dto.Steps, Ingredients = dto.Ingredients, MealTypes = dto.MealTypes }); }
public async void DoesValidatorPreventFromCreatingRecipeWithoutIngredients() { var request = new CreateRecipe { Name = "sample-name", Description = "sample-description", PictureUrl = "https://example.com/sample-image.png", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "Sample first step", "Sample second step" } }; var validator = new CreateRecipeValidator(); var result = await validator.ValidateAsync(request); result.IsValid.Should().BeFalse(); }
public async void DoesValidatorPreventFromCreatingRecipeWithTooLongDescription() { var request = new CreateRecipe { Name = "sample-name", Description = string.Concat(Enumerable.Repeat("a", 70000)), PictureUrl = "https://example.com/sample-image.png", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "1. Sample first step.", "2. Sample second step." }, Ingredients = new[] { "Sample first ingredient", "Sample second ingredient" } }; var validator = new CreateRecipeValidator(); var result = await validator.ValidateAsync(request); result.IsValid.Should().BeFalse(); }
public async void DoesValidatorAllowCorrectRequest() { var request = new CreateRecipe { Name = "sample-name", Description = "sample-description", PictureUrl = "https://example.com/sample-image.png", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "1. Sample first step.", "2. Sample second step." }, Ingredients = new[] { "Sample first ingredient", "Sample second ingredient" } }; var validator = new CreateRecipeValidator(); var result = await validator.ValidateAsync(request); result.IsValid.Should().BeTrue(); }
public async Task <IHttpActionResult> CreateRecipe(CreateRecipe model) { //check if model is valid if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //instantiate the service RecipeServices service = CreateRecipeService(); if (await service.CreateRecipe(model) == false) { return(InternalServerError()); } return(Ok()); }
public async void DoesValidatorPreventFromCreatingRecipeWithInvalidPictureUrl() { var request = new CreateRecipe { Name = "sample-name", Description = "sample-description", PictureUrl = "this-is-not-a-uri", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "1. Sample first step.", "2. Sample second step." }, Ingredients = new[] { "Sample first ingredient", "Sample second ingredient" } }; var validator = new CreateRecipeValidator(); var result = await validator.ValidateAsync(request); result.IsValid.Should().BeFalse(); }
public void Does_Map_Create_Not_Throw_Exception_When_No_Steps_Are_Null() { var dto = new CreateRecipe { Name = "Pizza Hawajska", Calories = 1200, Description = "Smaczna i zdrowa!", MealTypes = new[] { MealType.Snack, MealType.Lunch }, PictureUrl = "https://localhost:5001/img/pizza_hawajska.png" //No Steps -> Steps = null }; var entityId = Guid.Parse("be3dc63e-8f22-4d05-84b1-5fa6f4f652c4"); var userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2"; var date = new DateTime(2020, 10, 10, 5, 2, 1); Action a = () => _mapper.Map(dto, entityId, date, userId); a.Should().NotThrow(); }
public void Does_Map_Create_Not_Throw_Exception_When_Ingredients_Are_Null() { var dto = new CreateRecipe { Name = "Pizza Hawajska", Calories = 1200, Description = "Smaczna i zdrowa!", MealTypes = new[] { MealType.Snack, MealType.Lunch }, PictureUrl = "https://localhost:5001/img/pizza_hawajska.png", Steps = new[] { "Go into website and order it via phone!", "Wait for pizza boy to come and collect it from him." } }; var entityId = Guid.Parse("be3dc63e-8f22-4d05-84b1-5fa6f4f652c4"); var userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2"; var date = new DateTime(2020, 10, 10, 5, 2, 1); Action a = () => _mapper.Map(dto, entityId, date, userId); a.Should().NotThrow(); }
public async Task <Recipe> AddAsync(CreateRecipe command, User user) { var recipe = new Recipe(command.Name, command.Description, command.IsLactoseFree, command.IsGlutenFree, command.IsVegan, command.IsVegetarian); var components = CreateComponentsFromCommand(command.Components); await _context.Components.AddRangeAsync(components); recipe.Components = components; await _context.Recipes.AddAsync(recipe); user.Recipes.Add(recipe); await _context.SaveChangesAsync(); return(recipe); }
public async Task <IActionResult> Create([FromBody] CreateRecipe dto) { if (dto == null) { return(BadRequest()); } try { dto.UserId = IdentityHelper.GetUserId(User); } catch (UnauthorizedAccessException) { return(Unauthorized()); } int id = await _recipeService.CreateAsync(dto, _createRecipeValidator); return(StatusCode(201, id)); }
public async Task <bool> CreateRecipe(CreateRecipe model)//This needs vaification on the contoler to make sure the name of the measurement and ingredant esist { using (var ctx = new ApplicationDbContext()) { int MeasurementId = ctx .Measurements .Where(e => e.Name == model.MeasurementName) .Select( e => e.MeasurementId ).FirstOrDefault(); int IngredientId = ctx .Ingredients .Where(e => e.Name == model.IngredientName) .Select( e => e.IngredientId ).FirstOrDefault(); var entity = new Recipe() { OwnerId = _userId, Name = model.Name, Instructions = model.Instructions, Ingredients = new Dictionary <int, List <int> >() { { 1, new List <int> { IngredientId, MeasurementId, model.Quanity } } }, }; ctx.Recipes.Add(entity); return(await ctx.SaveChangesAsync() == 1); } }
public async void ShouldCreateRecipeCorrectly() { var command = new CreateRecipe { Name = "sample-name", Description = "sample-description", PictureUrl = "https://example.com/sample-image.png", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "1. Sample first step.", "2. Sample second step." }, Ingredients = new[] { "Sample first ingredient", "Sample second ingredient" } }; var eventStore = new Mock <IEventStore <Recipe> >(); var handler = new CreateRecipeHandler(eventStore.Object, MockBuilder.BuildFakeRecipeEventsMapper(), MockBuilder.BuildFakeCurrentUserService(), MockBuilder.BuildFakeDateTimeService()); await handler.Handle(command, CancellationToken.None); var expected = new RecipeCreated { EntityId = new Guid("7ADC9EF0-6A2A-4DE5-9C27-D4C2A4D9D5B6"), Published = new DateTime(2010, 1, 1), Version = 0, AuthorId = "9E09950B-47DE-4BAB-AA79-C29414312ECB", Name = "sample-name", Description = "sample-description", PictureUrl = "https://example.com/sample-image.png", Calories = 1234, MealTypes = new[] { MealType.Snack }, Steps = new[] { "1. Sample first step.", "2. Sample second step." }, Ingredients = new[] { "Sample first ingredient", "Sample second ingredient" } }; eventStore.Verify(x => x.AddEvent(It.Is <RecipeCreated>(y => y.WithDeepEqual(expected).IgnoreSourceProperty(z => z.EntityId).Compare() ))); }
public Task <Recipe> CreateRecipe(string userId, CreateRecipe createRecipe) { throw new System.NotImplementedException(); }
public async Task <ApiResult <GetCreateRecipe> > Create(CreateRecipe bundle) { var count = _context.Recipes.Where(x => x.IdProduct == bundle.IdProduct).Count(); if (count < 1) { bundle.Prioritize = true; } if (bundle.Prioritize) { var check = await _context.Recipes .AnyAsync(x => x.IdProduct == bundle.IdProduct && x.Prioritize == true); if (check) { var reciper = await _context.Recipes .FirstAsync(x => x.IdProduct == bundle.IdProduct && x.Prioritize == true); reciper.Prioritize = false; _context.Recipes.Update(reciper); } } var recipeDetail = new List <RecipeDetail>(); if (bundle.IdMaterials != null) { int i = 0; foreach (int item in bundle.IdMaterials) { recipeDetail.Add(new RecipeDetail() { IdMaterials = item, Amount = bundle.Amount[i], Unit = bundle.Unit[i] }); i++; } } var recipe = new Recipe() { Name = bundle.Name, Note = bundle.Note, Prioritize = bundle.Prioritize, IdProduct = bundle.IdProduct, RecipeDetails = recipeDetail }; var code = await _context.ManageCodes.FirstOrDefaultAsync(x => x.Name == bundle.Code); var stt = 1; Location: var location = code.Location + stt; var str = code.Name + location; var checkCode = await _context.Recipes.AnyAsync(x => x.Code == str); if (checkCode) { stt++; goto Location; } code.Location = location; _context.ManageCodes.Update(code); await _context.SaveChangesAsync(); recipe.Code = str; _context.Recipes.Add(recipe); await _context.SaveChangesAsync(); var result = new GetCreateRecipe() { IdProduct = recipe.IdProduct, NameRecipe = recipe.Name, Prioritize = recipe.Prioritize }; return(new ApiSuccessResult <GetCreateRecipe>(result)); }
private void ShowRecipeCreator(object sender, EventArgs e) { CreateRecipe recipeCreator = new CreateRecipe(_chosenBook, LoadCurrentRecipes); Navigate(recipeCreator); }
public async Task <IActionResult> Create(CreateRecipe bundle) { var result = await _recipeApiClient.CreateRecipe(bundle); return(Ok(result)); }
/// <summary> /// Event déclenché pour l'ouverture de la fenêtre de création des recettes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CrerRec(object sender, RoutedEventArgs e) { CreateRecipe newRecipe = new CreateRecipe(idcdr, client, id); newRecipe.Show(); }
public virtual HttpResponseMessage Post(Guid id, CreateRecipe createRecipe) { throw new NotImplementedException(); }