public int Create([FromBody] CreateRecipeCommand cmd) { Console.WriteLine("creating recipe...{0}", cmd); var newId = service.When(cmd.ToInternal()); return(newId); }
public void SetUp() { _ingredientRepository = new Mock <IIngredientRepository>(); _recipeFactoryMock = new Mock <IRecipeFactory>(); _eventPublisherMock = new Mock <IEventPublisher>(); _recipeFactoryMock = new Mock <IRecipeFactory>(); _imageUploaderMock = new Mock <IImageUploader>(); var commandValidator = new Mock <ICommandValidator <CreateRecipeCommand> >(); commandValidator.Setup(x => x.Validate(It.IsAny <CreateRecipeCommand>())) .Returns(Result.Ok); _commandValidators = new List <ICommandValidator <CreateRecipeCommand> > { commandValidator.Object }; _ingredientRepository.Setup(x => x.ExistById(It.IsAny <Guid>())) .Returns(true); _commandsFactory = new CommandsFactory(_ingredientRepository.Object); _command = _commandsFactory.CreateRecipeCommand("name", "description"); _systemUnderTests = new CreateRecipeCommandHandler( _commandValidators, _eventPublisherMock.Object, _recipeFactoryMock.Object, _recipeIngredientFactoryMock.Object, _imageUploaderMock.Object); }
public async Task <IActionResult> Create(CreateRecipeCommand command) { try { if (ModelState.IsValid) { var appUser = await _userService.GetUserAsync(User); var id = _service.CreateRecipe(command, appUser); return(RedirectToAction(nameof(View), new { id = id })); } } catch (Exception) { // TODO: Log error // Add a model-level error by using an empty string key ModelState.AddModelError( string.Empty, "An error occured saving the recipe" ); } //If we got to here, something went wrong return(View(command)); }
public async Task <IActionResult> Create(CreateRecipeCommand cmd) { try { if (ModelState.IsValid) { User user = await _userService.GetUserAsync(User); int recipeId = await _recipeService.CreateRecipeAsync(cmd, user); _logger.LogInformation("Recipe with ID {Id} has been created", recipeId); return(RedirectToAction(nameof(Details), new { Id = recipeId })); } else { _logger.LogWarning("Creating recipe is failed due to invalid ModelState", cmd.Name); } } catch (Exception ex) { ModelState.AddModelError(string.Empty, "An error occured saving the recipe"); _logger.LogError("Failed to save the recipe. Recipe name = {RecipeName}\nException: {Exception}", cmd.Name, ex); } return(View(cmd)); }
/// <summary> /// Create a new recipe /// </summary> /// <param name="cmd"></param> /// <returns>The id of the new recipe</returns> public int CreateRecipe(CreateRecipeCommand cmd, ApplicationUser createdBy) { var recipe = cmd.ToRecipe(createdBy); _context.Add(recipe); _context.SaveChanges(); return(recipe.RecipeId); }
public static CreateRecipe ToInternal(this CreateRecipeCommand c) { return(new CreateRecipe { Name = c.name, Category = c.category, UserName = c.userName }); }
/// <summary> /// Create a new recipe /// </summary> /// <param name="cmd"></param> /// <returns>The id of the new recipe</returns> public int CreateRecipe(CreateRecipeCommand cmd) { var recipe = cmd.ToRecipe(); _context.Add(recipe); _context.SaveChanges(); return(recipe.RecipeId); }
/// <summary> /// Create a new recipe /// </summary> /// <param name="cmd"></param> /// <returns>The id of the new recipe</returns> public async Task <int> CreateRecipe(CreateRecipeCommand cmd, ApplicationUser createdBy) { var recipe = cmd.ToRecipe(createdBy); _context.Add(recipe); await _context.SaveChangesAsync(); return(recipe.RecipeId); }
/// <summary> /// Create a new recipe /// </summary> /// <param name="cmd"></param> /// <returns>The id of the new recipe</returns> public async Task <int> CreateRecipe(CreateRecipeCommand cmd) { var recipe = cmd.ToRecipe(); _context.Add(recipe); recipe.LastModified = DateTimeOffset.UtcNow; await _context.SaveChangesAsync(); return(recipe.RecipeId); }
public async Task <int> CreateRecipeAsync(CreateRecipeCommand cmd, User user) { var recipe = _mapper.Map <Recipe>(cmd); recipe.CreatedById = user.Id; await _context.Recipes.AddAsync(recipe); await _context.SaveChangesAsync(); return(recipe.RecipeId); }
public async override Task <string> Handle(CreateRecipeCommand request, CancellationToken cancellationToken) { Entity = mapper.Map <CreateRecipeCommand, Recipe>(request); logger.LogInformation("Recipe Add", Entity, request); Result = repo.Add(Entity); logger.LogInformation("Recipe Add", Result); return(Result); }
public int CreateRecipe(CreateRecipeCommand cmd) { var recipe = new Recipe { Name = cmd.Name, TimeToCook = new TimeSpan(100), Method = cmd.Method, Ingredients = cmd.Ingredients?.Select(i => new Ingredient { Name = i.Name, Quantity = i.Quantity, Unit = i.Unit }).ToList() }; _context.Add(recipe); _context.SaveChanges(); return(recipe.RecipeId); }
public void CreateRecipeCommand_Succeeds() { var command = new CreateRecipeCommand(_mockRepository.Object, new Recipe { Id = 1, Title = "Homemade Pizza", Description = "Pizza Made At Home", TimeToPrepare = 1.5 }); command.Execute(); _mockRepository.Verify(r => r.Create(It.Is <Recipe>(rec => rec.Id == 1 && rec.Title == "Homemade Pizza" && rec.Description == "Pizza Made At Home" && rec.TimeToPrepare == 1.5)), Times.Once()); _mockRepository.Verify(r => r.SaveChanges(), Times.Once()); }
public async Task ARecipeIsCreated() { var cmd = new CreateRecipeCommand { Name = "Chocolate Cake", Description = "Best birthday cake", PrepTime = Duration.FromMinutes(15), CookTime = Duration.FromHours(1) }; var result = await AppFixture.SendAsync(cmd); result.Key.Should().NotBe(Guid.Empty); result.Version.Should().Be(1); var saved = await AppFixture.FindAsync <Recipe>(result.Key); saved.Name.Should().Be("Chocolate Cake"); saved.Description.Should().Be("Best birthday cake"); saved.CookTime.Should().Be(Duration.FromMinutes(60)); }
public RecipeDto CreateRecipe(string itemName, int?created, IEnumerable <IngredientDto> ingredientsDto) { var item = GetCreateItem(itemName); var ingredients = ingredientsDto.Select(GetCreateIngredient); var entries = ingredients.Select(CreateIngredient); var recipe = new Recipe { Item = item, RecipeIngredients = entries.ToList(), Created = created }; ICreateRecipeCommand cmd = new CreateRecipeCommand(Access); cmd.CreateRecipe(recipe); Access.Save(); var dto = new RecipeDto { Id = recipe.Id }; return(dto); }
public async Task CreateRecipe_NewRecipe_SuccessfullRead() { IServiceCollection services = new ServiceCollection(); services.AddKitchenDomain() .AddKitchenApplication() .AddKitchenInfrastructure("Server=.;Database=RestaurantManagementSystem;Trusted_Connection=True;MultipleActiveResultSets=true", "S0M3 M4G1C UN1C0RNS G3N3R4T3D TH1S S3CR3T"); var serviceProviderFactory = new DefaultServiceProviderFactory(); IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(services); IMediator Mediator = serviceProvider.GetService <IMediator>(); var createRecipeCommand = new CreateRecipeCommand(); createRecipeCommand.Name = "Mandja"; createRecipeCommand.Description = "Vkusno"; createRecipeCommand.Preparation = "Gotvish"; createRecipeCommand.Ingredients.Add(new Ingredient("Qdene", 500)); CreateRecipeOutputModel createRecipeOutput; createRecipeOutput = await Mediator.Send(createRecipeCommand); var recipiesQuery = new GetRecipesQuery(); recipiesQuery.OnlyActive = true; var recipesResult = await Mediator.Send(recipiesQuery); var recipe = recipesResult.Recipes.FirstOrDefault(recipe => recipe.Id == createRecipeOutput.RecipeId); Assert.AreEqual(createRecipeCommand.Name, recipe.Name); Assert.AreEqual(createRecipeCommand.Description, recipe.Description); Assert.AreEqual(createRecipeCommand.Preparation, recipe.Preparation); }
public async Task <IActionResult> CreateRecipe([FromForm] IFormFile File, [FromBody] CreateRecipeCommand command) { command.Image = File; var validationResult = _validators.ValidateCreate(command); if (!validationResult.IsValid) { return(BadRequest(validationResult)); } var result = await _mediator.Command(command); if (result.IsSuccess) { return(Created($"api/recipe{command.Id.ToString()}", result)); } if (result.ResultCode.Equals(ResultCode.NotFound)) { return(NotFound(result)); } return(BadRequest(result)); }
public async Task CreateRecipe_InsertsNewRecipe() { const string recipeName = "Test Recipe"; var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder <AppDbContext>() .UseSqlite(connection) .Options; // Run the test against one instance of the context using (var context = new AppDbContext(options)) { context.Database.EnsureCreated(); var service = new RecipeService(context); var cmd = new CreateRecipeCommand { Name = recipeName, }; var user = new ApplicationUser { Id = 123.ToString() }; var recipeId = service.CreateRecipe(cmd, user); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new AppDbContext(options)) { Assert.Equal(1, await context.Recipes.CountAsync()); var recipe = await context.Recipes.SingleAsync(); Assert.Equal(recipeName, recipe.Name); } }
public ValidationResult ValidateCreate(CreateRecipeCommand command) => _createValidator.Validate(command);
public async Task <ActionResult <RecipeDto> > CreateProduct(CreateRecipeCommand request) { var result = await Mediator.Send(request); return(GetResponse(result)); }
public async Task <ActionResult <int> > Post([FromBody] CreateRecipeCommand command) { int id = await mediator.Send(command); return(Ok(id)); }
public async Task <ActionResult <CreateRecipeOutputModel> > CreateRecipe(CreateRecipeCommand createRecipeCommand) { return(await Send(createRecipeCommand)); }
public void OnGet() { Input = new CreateRecipeCommand(); }
public async Task <IActionResult> Create([FromBody] CreateRecipeCommand command) { var result = await Mediator.Send(command); return(Ok(result)); }