Ejemplo n.º 1
0
        public int Create([FromBody] CreateRecipeCommand cmd)
        {
            Console.WriteLine("creating recipe...{0}", cmd);
            var newId = service.When(cmd.ToInternal());

            return(newId);
        }
Ejemplo n.º 2
0
        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));
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 8
0
        /// <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);
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        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);
Ejemplo n.º 20
0
        public async Task <ActionResult <RecipeDto> > CreateProduct(CreateRecipeCommand request)
        {
            var result = await Mediator.Send(request);

            return(GetResponse(result));
        }
Ejemplo n.º 21
0
        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));
 }
Ejemplo n.º 23
0
 public void OnGet()
 {
     Input = new CreateRecipeCommand();
 }
Ejemplo n.º 24
0
        public async Task <IActionResult> Create([FromBody] CreateRecipeCommand command)
        {
            var result = await Mediator.Send(command);

            return(Ok(result));
        }