Ejemplo n.º 1
0
        // Insert new recipe service
        public int InsertRecipe(CreateRecipeRequest Model) // post
        {
            int _id = 0;

            DataProvider.ExecuteNonQuery(GetConnection, "dbo.Recipes_Insert"
                                         , inputParamMapper : delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@name", Model.Name);
                paramCollection.AddWithValue("@directions", Model.Directions);
                paramCollection.AddWithValue("@preptime", Model.PrepTime);
                paramCollection.AddWithValue("@totaltime", Model.TotalTime);
                paramCollection.AddWithValue("@numberofservings", Model.NumberOfServings);
                paramCollection.AddWithValue("@userid", Model.UserId);
                paramCollection.AddWithValue("@description", Model.Description);
                SqlParameter p = new SqlParameter("@id", System.Data.SqlDbType.Int);
                p.Direction    = System.Data.ParameterDirection.Output;

                paramCollection.Add(p);
            },
                                         returnParameters : delegate(SqlParameterCollection param)
            {
                int.TryParse(param["@Id"].Value.ToString(), out _id);
            }
                                         );

            return(_id);
        }
Ejemplo n.º 2
0
        public async Task <Recipe> CreateRecipe(Recipe recipe)
        {
            var request = new CreateRecipeRequest
            {
                Name      = recipe.Name,
                Author    = recipe.Author,
                UserId    = recipe.UserId,
                Style     = recipe.Style,
                BatchSize = recipe.BatchSize
            };

            var result = await _recipeServiceClient.Create(request);

            return(new Recipe
            {
                Id = result.Id,
                Name = result.Name,
                Author = result.Author,
                UserId = result.UserId,
                Style = result.Style,
                BatchSize = result.BatchSize,
                CreatedAt = result.CreatedAt,
                UpdatedAt = result.UpdatedAt
            });
        }
Ejemplo n.º 3
0
        public HttpResponseMessage PostRecipe(CreateRecipeRequest model)
        {
            ItemResponse <int> ItemResponse = new ItemResponse <int>();

            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            // if model valid, then we will pass this into the recipe service interface
            try
            {
                model.UserId = UserService.GetCurrentUserId();

                int RecipeId = _RecipesService.InsertRecipe(model);

                _IngredientsService.InsertIngredient(model.Ingredients, RecipeId);

                ItemResponse.Item = RecipeId;
            }

            // Display error code and message if user was not created
            catch (IdentityResultException)
            {
                var ExceptionError = new Models.Responses.ErrorResponse("Identity Result Exception Detected");

                return(Request.CreateResponse(HttpStatusCode.BadRequest, ExceptionError));
            }


            return(Request.CreateResponse(HttpStatusCode.OK, ItemResponse));
        }
Ejemplo n.º 4
0
        public async Task <RecipeDetailsResponse> Create(CreateRecipeRequest request)
        {
            using var client = CreateClient();

            var result = await client.PostJsonAsync($"/v1/recipe", request);

            return(await result.Content.ReadAsAsync <RecipeDetailsResponse>());
        }
Ejemplo n.º 5
0
        public async void CreateRecipe_WillReturn201()
        {
            var recipe = new CreateRecipeRequest
            {
                Name      = "My new recipe!",
                Author    = "*****@*****.**",
                UserId    = "auth0|foobar",
                BatchSize = 20.5,
                Style     = "Belgian Pale Ale"
            };

            _mockProviderService
            .Given("There is no recipes for panomies")
            .UponReceiving("POST to create recipe")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Post,
                Path   = "/v1/recipe",
                Body   = new {
                    name      = "My new recipe!",
                    author    = "*****@*****.**",
                    userId    = "auth0|foobar",
                    batchSize = 20.5,
                    style     = "Belgian Pale Ale"
                },
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" },
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 201,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json" }
                },
                Body = new {
                    name         = "My new recipe!",
                    author       = "*****@*****.**",
                    userId       = "auth0|foobar",
                    batchSize    = 20.5,
                    style        = "Belgian Pale Ale",
                    hops         = new string[] {},
                    fermentables = new string[] {}
                }
            });

            var consumer = CreateConsumer();
            var result   = await consumer.Create(recipe);

            Assert.Equal(recipe.Name, result.Name);
            _mockProviderService.VerifyInteractions();
        }
Ejemplo n.º 6
0
    public Recipe Post(CreateRecipeRequest request)
    {
        // Convert the flat CreateRecipeRequest object to a structured Recipe object
        // Steps
        int numberOfSteps = request.StepName.Length;
        // Ingredients
        int numberOfIngredients = request.IngredientName.Length;

        // Check there is a description and duration for all steps
        if (request.StepDescription == null || request.StepDescription.Length != numberOfSteps || request.StepDuration == null || request.StepDuration.Length != numberOfSteps)
        {
            throw new Exception("There must be a duration and description for all steps");
        }
        // Create the Recipe object
        var recipe = new Recipe {
            Name = request.Name, Steps = new Step[numberOfSteps], Ingredients = new Ingredient[numberOfIngredients]
        };

        for (int s = 0; s < numberOfSteps; s++)
        {
            recipe.Steps[s] = new Step {
                Name = request.StepName[s], Description = request.StepDescription[s], Duration = request.StepDuration[s]
            }
        }
        ;
        // Check there is a quantity type and quantity value for all ingredients
        if (request.IngredientQuantityName == null || request.IngredientQuantityName.Length != numberOfIngredients || request.IngredientQuantityValue == null || request.IngredientQuantityValue.Length != numberOfIngredients)
        {
            throw new Exception("The quantity must be provided for each ingredient");
        }
        for (int i = 0; i < numberOfIngredients; i++)
        {
            recipe.Ingredients[i] = new Ingredient {
                Name = request.IngredientName[i], QuantityName = request.IngredientQuantityName[i], Quantity = request.IngredientQuantityValue[i]
            }
        }
        ;

        /*
         * Recipe can now be accessed through a logical collection:
         *
         * recipe.Name
         * recipe.Steps[0].Name
         * recipe.Ingredients[1].Quantity
         *
         */
        return(recipe);
    }
}
Ejemplo n.º 7
0
        public async Task <IActionResult> Create([FromBody] CreateRecipeRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Name) ||
                string.IsNullOrWhiteSpace(request.Issuer))
            {
                return(BadRequest());
            }

            using var transaction = await this._transactionProvider.BeginTransaction();

            var recipe = await this._service.InsertItem(request.Name, request.Address, request.Issuer, request.PZNs);

            await transaction.CommitAsync();

            return(Ok(this._mapper.Map <RecipeDTO>(recipe)));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Create([FromBody] CreateRecipeRequest recipeRequest)
        {
            if (recipeRequest.Name == null || recipeRequest.Description == null)
            {
                return(BadRequest(new { error = "Null variables [Name and Description] are not allowed" }));
            }

            var recipe = new Recipe
            {
                Id          = new int(),
                Name        = recipeRequest.Name,
                Description = recipeRequest.Description,
                Date        = DateTime.UtcNow,
                ParentId    = recipeRequest.ParentId,
                Left        = 1,
                Right       = 2,
                DepthLevel  = 0,
                TreeId      = Guid.NewGuid()
            };

            if (recipe.ParentId != null)
            {
                var parentRecipe = await _recipeService.GetRecipeByIdAsync((int)recipe.ParentId);

                recipe.DepthLevel = parentRecipe.DepthLevel + 1;
                recipe.TreeId     = parentRecipe.TreeId;
                recipe.Left       = await _recipeService.FindLeftAtSpecificDeep(recipe.DepthLevel, recipe.TreeId, (int)recipe.ParentId);

                recipe.Right = recipe.Left + 1;
                await _recipeService.IncrementAllPositionsWhenRecipeAdded(recipe.Right, recipe.TreeId, (int)recipe.ParentId);
            }
            await _recipeService.CreateRecipeAsync(recipe);

            var response = new RecipeResponse
            {
                Id          = recipe.Id,
                Name        = recipe.Name,
                Description = recipe.Description,
                Date        = recipe.Date,
                ParentId    = recipe.ParentId,
                DepthLevel  = recipe.DepthLevel,
                TreeId      = recipe.TreeId
            };

            return(Ok(response));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Create([FromBody] CreateRecipeRequest request)
        {
            /*   var recipe = new Recipe
             * {
             *    Title = request.Title,
             *    Summary = request.Summary,
             *    Directions = request.Directions,
             *    Ingredients = request.Ingredients,
             *    NutritionInfo = request.NutritionInfo
             * }; */

            var recipe = _mapper.Map <Recipe>(request);

            repository.Add(recipe);

            if (await repository.SaveAll())
            {
                return(Ok());
            }

            throw new Exception(GlobalConstants.ERROR_SAVING_CHANGES);
        }
 public IActionResult Create([FromBody] CreateRecipeRequest request, [FromHeader] User user)
 {
     recipeService.CreateRecipe(request, user);
     return(ActionUtils.Success("Recipe has been created"));
 }
Ejemplo n.º 11
0
        public void CreateRecipe(CreateRecipeRequest request, User user)
        {
            if (request == null)
            {
                throw new ActionFailedException("invalid request body");
            }
            if (string.IsNullOrWhiteSpace(request.Title))
            {
                throw new ActionFailedException("title cannot be empty");
            }
            if (string.IsNullOrWhiteSpace(request.Text))
            {
                throw new ActionFailedException("title cannot be empty");
            }

            request.Title = request.Title.Trim();
            request.Text  = request.Text.Trim();

            if (request.Title.Length < 4)
            {
                throw new ActionFailedException("title is too short");
            }
            if (request.Text.Length < 6)
            {
                throw new ActionFailedException("recipe details is too short");
            }

            if (request.Portion <= 0)
            {
                throw new ActionFailedException("portion cannot be smaller than 1");
            }
            if (request.Portion > 200)
            {
                throw new ActionFailedException("portion is too large");
            }

            if (request.PrepareTime <= 0)
            {
                throw new ActionFailedException("prepare time cannot be smaller than 1");
            }
            if (request.PrepareTime > 600)
            {
                throw new ActionFailedException("prepare time is too large");
            }

            if (request.Ingredients == null)
            {
                request.Ingredients = new string[0];
            }
            if (request.Steps == null)
            {
                request.Steps = new string[0];
            }

            foreach (var item in request.Steps)
            {
                if (string.IsNullOrWhiteSpace(item))
                {
                    throw new ActionFailedException("step items cannot be empty");
                }
            }

            if (request.Photos == null)
            {
                request.Photos = new List <string>();
            }
            if (request.Tags == null)
            {
                request.Tags = new string[0];
            }

            //if (request.Photos.Count == 0)
            //    throw new ActionFailedException("Select at least one image");

            Recipe recipe = new Recipe();

            recipe.Id           = 0;
            recipe.Title        = request.Title;
            recipe.Text         = request.Text;
            recipe.Ingredients  = JsonConvert.SerializeObject(request.Ingredients);
            recipe.Steps        = JsonConvert.SerializeObject(request.Steps);
            recipe.CreatedTime  = DateTime.Now;
            recipe.ModifiedTime = DateTime.Now;
            recipe.Portion      = request.Portion;
            recipe.PrepareTime  = request.PrepareTime;
            recipe.User         = user;
            recipe.Photos       = JsonConvert.SerializeObject(request.Photos);
            recipe.RecipeTags   = new List <RecipeTag>();
            recipeContext.Recipes.Add(recipe);
            recipeContext.SaveChanges();

            foreach (var item in request.Tags)
            {
                if (string.IsNullOrWhiteSpace(item))
                {
                    throw new ActionFailedException("tags cannot be empty");
                }

                var tagText = item.ToLower();
                Tag tag     = recipeContext.Tags.FirstOrDefault(x => x.Text == tagText);
                if (tag == null)
                {
                    tag      = new Tag();
                    tag.Text = tagText;
                    recipeContext.Tags.Add(tag);
                    recipeContext.SaveChanges();
                }

                recipe.RecipeTags.Add(new RecipeTag {
                    Recipe   = recipe,
                    Tag      = tag,
                    RecipeId = recipe.Id,
                    TagId    = tag.Id
                });
            }

            recipeContext.SaveChanges();
        }
Ejemplo n.º 12
0
        public async Task <ActionResult <RecipeResponse> > CreateRecipeAsync(CreateRecipeRequest request, [FromServices] Command <CreateRecipeRequest, RecipeResponse> command)
        {
            var response = await command.ExecuteAsync(request);

            return(CreatedAtRoute("GetSingleRecipe", new { recipeId = response.Id }, response));
        }