コード例 #1
0
        public void Does_Map_Update_Recipe_Work_Correctly()
        {
            var dto = new UpdateRecipe
            {
                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" }
            };
            var expected = new RecipeUpdated
            {
                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),
            };
            var userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2";
            var date   = new DateTime(2020, 10, 10, 5, 2, 1);

            var result = _mapper.Map(dto, date, userId);

            result.Should().BeEquivalentTo(expected);
        }
コード例 #2
0
        // GET: Recipe/Edit/5
        public ActionResult Edit(int id)
        {
            UpdateRecipe ViewModel = new UpdateRecipe();

            string url = "recipedata/findrecipe/" + id;
            HttpResponseMessage response = client.GetAsync(url).Result;

            //Can catch the status code (200 OK, 301 REDIRECT), etc.
            //Debug.WriteLine(response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                //Put data into recipe data transfer object
                RecipeDto SelectedRecipes = response.Content.ReadAsAsync <RecipeDto>().Result;
                ViewModel.recipe = SelectedRecipes;

                //get information about dish this recipe COULD be used for.
                url      = "dishdata/getdishes";
                response = client.GetAsync(url).Result;
                IEnumerable <DishesDto> PotentialDishes = response.Content.ReadAsAsync <IEnumerable <DishesDto> >().Result;
                ViewModel.alldishes = PotentialDishes;

                return(View(ViewModel));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
コード例 #3
0
        public RecipeControllerTest()
        {
            //mock setup
            RecipeMock  = new Mock <IRecipe>();
            RecipesMock = new List <IRecipe> {
                RecipeMock.Object
            };
            updateRecipeMock = new Mock <IUpdateRecipe>();
            Recipe           = new Recipe();
            Recipes          = new List <Recipe>();
            //viewmodels mock setup


            //sample models
            updateRecipe = new UpdateRecipe {
            };

            //controller setup
            var RecipeResultsMock = new Mock <IActionResult>();

            mockRepo = new Mock <IRepositoryWrapper>();
            var allRecipes = AllRecipes();

            recipeController = new RecipeController(mockRepo.Object);
        }
コード例 #4
0
        public void Handle(UpdateRecipe recipeData)
        {
            FileInfo fi = new FileInfo(@"../../Recipe/Recipe.txt");

            if (fi.Exists)
            {
                StreamReader RecipeRead    = File.OpenText(@"../../Recipe/Recipe.txt");
                string       compareRecipe = RecipeRead.ReadToEnd();
                RecipeRead.Close();
                if (recipe != recipeData.Recipe)
                {
                    recipe = recipeData.Recipe;
                    Console.WriteLine("Replace the recipe.");
                    StreamWriter sw = new StreamWriter(@"../../Recipe/Recipe.txt");
                    sw.Write(recipe);

                    for (int i = 0; i < _localCount; i++)
                    {
                        if (!_localManager[i].IsTerminated)
                        {
                            _logger.Info("Send updated recipes");
                            _localManager[i].MyLocalActor.Tell(new RestartMonitor(recipe));
                        }
                    }

                    sw.Close();
                }
                else
                {
                    Console.WriteLine("The recipe is the same.");
                }
            }
            Sender.Tell(new RecipeUpdated());
        }
コード例 #5
0
        public async Task <ApiResult <GetCreateRecipe> > Update(UpdateRecipe bundle)
        {
            var json        = JsonConvert.SerializeObject(bundle);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var url         = $"/api/recipe";
            var result      = await Update <GetCreateRecipe>(url, httpContent);

            return(result);
        }
コード例 #6
0
        //we can have roles to each endpoint
        // [Authorize(Roles = "Administrator")]
        public async Task <IActionResult> UpdateRecipe(Guid id, [FromBody] UpdateRecipe updateRecipe, CancellationToken cancellationToken)
        {
            var updateRecipeCommand = updateRecipe with {
                Id = id
            };
            var result = await _mediator.Send(updateRecipeCommand, cancellationToken);

            return(new StatusCodeResult((int)result.StatusCode));
        }
    }
コード例 #7
0
 public async Task <IActionResult> ChangeRecipe([FromBody] UpdateRecipe input)
 {
     return(await SendCommandAsync(new ChangeRecipe(
                                       PeriodId.From(input.PeriodId),
                                       OperationId.From(input.OperationId),
                                       Amount.From(input.Amount),
                                       Label.From(input.Label),
                                       Pair.From(input.Pair),
                                       RecipeCategory.From(input.Category))));
 }
コード例 #8
0
        public async Task <IActionResult> UpdateRecipeAsync(int id, int recipeId, [FromBody] UpdateRecipe command)
        {
            if (id != AccountID)
            {
                return(Forbid());
            }

            await _recipeService.UpdateAsync(command, recipeId);

            return(NoContent());
        }
コード例 #9
0
        // GET: Recipe/Create
        public ActionResult Create()
        {
            UpdateRecipe ViewModel = new UpdateRecipe();
            //get information about dish this recipe COULD be used for.
            string url = "dishdata/getdishes";
            HttpResponseMessage     response        = client.GetAsync(url).Result;
            IEnumerable <DishesDto> PotentialDishes = response.Content.ReadAsAsync <IEnumerable <DishesDto> >().Result;

            ViewModel.alldishes = PotentialDishes;

            return(View(ViewModel));
        }
コード例 #10
0
        public async Task <IActionResult> Update([FromBody] UpdateRecipe bundle)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _recipeService.Update(bundle);

            if (!result.IsSuccessed)
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
コード例 #11
0
 public virtual RecipeUpdated Map(UpdateRecipe dto, DateTime publishTime, string userId)
 {
     return(new RecipeUpdated
     {
         Name = dto.Name,
         EntityId = dto.EntityId,
         Published = publishTime,
         AuthorId = userId,
         Description = dto.Description,
         PictureUrl = dto.PictureUrl,
         Calories = dto.Calories,
         Steps = dto.Steps,
         Ingredients = dto.Ingredients,
         MealTypes = dto.MealTypes
     });
 }
コード例 #12
0
        public async void DoesValidatorPreventFromUpdatingRecipeWithoutSteps()
        {
            var request = new UpdateRecipe
            {
                EntityId    = new Guid("447EA0EF-F828-486A-91A9-0EDBC01D0B89"),
                Name        = "sample-name",
                Description = "sample-description",
                PictureUrl  = "https://example.com/sample-image.png",
                Calories    = 1234,
                MealTypes   = new[] { MealType.Snack }
            };
            var validator = new UpdateRecipeValidator(MockBuilder.BuildFakeRepository(), MockBuilder.BuildFakeCurrentUserService());

            var result = await validator.ValidateAsync(request);

            result.IsValid.Should().BeFalse();
        }
コード例 #13
0
        public void UpdateRecipeShouldBeValid()
        {
            // Should be valid
            var test1 = new UpdateRecipe
            {
                Id          = "test",
                Title       = "test",
                Description = "test",
                Notes       = "test"
            };

            var test1Validator = new UpdateRecipeValidator();

            Assert.True(test1Validator.Validate(test1).IsValid);

            // Should require title
            var test2 = new UpdateRecipe
            {
                Id          = "test",
                Description = "test",
                Notes       = "test"
            };

            var test2Validator = new UpdateRecipeValidator();

            test2Validator.ShouldHaveValidationErrorFor(c => c.Title, test2);

            var longTitle = "test";

            while (longTitle.Length <= 100)
            {
                longTitle += $"{longTitle}{longTitle}{longTitle}{longTitle}";
            }

            // title should be 100 in length
            var test3 = new UpdateRecipe
            {
                Id          = "test",
                Description = longTitle,
                Notes       = "test"
            };

            var test3Validator = new UpdateRecipeValidator();

            test3Validator.ShouldHaveValidationErrorFor(c => c.Title, test2);
        }
コード例 #14
0
        public async Task <IActionResult> Update([FromBody] UpdateRecipe dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            try
            {
                dto.UserId = IdentityHelper.GetUserId(User);
            }
            catch (UnauthorizedAccessException)
            {
                return(Unauthorized());
            }

            RecipeToNotify original = await _recipeService.UpdateAsync(dto, _updateRecipeValidator);

            // Notify
            var usersToBeNotified = await _userService.GetToBeNotifiedOfRecipeChangeAsync(original.Id, dto.UserId);

            if (usersToBeNotified.Any())
            {
                var currentUser = await _userService.GetAsync(dto.UserId);

                foreach (var user in usersToBeNotified)
                {
                    CultureInfo.CurrentCulture = new CultureInfo(user.Language, false);
                    var message = _localizer["UpdatedRecipeNotification", IdentityHelper.GetUserName(User), original.Name];

                    var pushNotification = new PushNotification
                    {
                        SenderImageUri = currentUser.ImageUri,
                        UserId         = user.Id,
                        Application    = "Cooking Assistant",
                        Message        = message
                    };

                    _senderService.Enqueue(pushNotification);
                }
            }

            return(NoContent());
        }
コード例 #15
0
        public async void DoesValidatorPreventFromUpdatingNotExistingRecipe()
        {
            var request = new UpdateRecipe
            {
                EntityId    = new Guid("1FED1A46-D5FF-4259-B838-08CA7C95F264"),
                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 UpdateRecipeValidator(MockBuilder.BuildFakeRepository(), MockBuilder.BuildFakeCurrentUserService());

            var result = await validator.ValidateAsync(request);

            result.IsValid.Should().BeFalse();
        }
コード例 #16
0
        public void Does_Map_Update_Not_Throw_Exception_When_No_Steps_Are_Null()
        {
            var dto = new UpdateRecipe()
            {
                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"
                              //No Steps -> Steps = null
            };
            var userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2";
            var date   = new DateTime(2020, 10, 10, 5, 2, 1);

            Action a = () => _mapper.Map(dto, date, userId);

            a.Should().NotThrow();
        }
コード例 #17
0
        public async void DoesValidatorPreventFromUpdatingRecipeWithNoDescription()
        {
            var request = new UpdateRecipe
            {
                EntityId    = new Guid("447EA0EF-F828-486A-91A9-0EDBC01D0B89"),
                Name        = "sample-name",
                Description = string.Empty,
                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 UpdateRecipeValidator(MockBuilder.BuildFakeRepository(), MockBuilder.BuildFakeCurrentUserService());

            var result = await validator.ValidateAsync(request);

            result.IsValid.Should().BeFalse();
        }
コード例 #18
0
        public void Does_Map_Update_Not_Throw_Exception_When_Ingredients_Are_Null()
        {
            var dto = new UpdateRecipe
            {
                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." }
            };
            var userId = "7f7dfc41-3b52-4c43-aef9-b82099a7beb2";
            var date   = new DateTime(2020, 10, 10, 5, 2, 1);

            Action a = () => _mapper.Map(dto, date, userId);

            a.Should().NotThrow();
        }
コード例 #19
0
        public async Task <ApiResult <GetCreateRecipe> > Update(UpdateRecipe bundle)
        {
            var data = await _context.Recipes.FindAsync(bundle.IdRecipe);

            data.IdProduct = bundle.IdProduct;
            data.Name      = bundle.Name;
            data.Note      = bundle.Note;

            _context.Recipes.Update(data);

            // thêm nguyên liệu
            if (bundle.IdMaterials != null)
            {
                int i = 0;
                foreach (int item in bundle.IdMaterials)
                {
                    var recipeDetail = new RecipeDetail()
                    {
                        IdMaterials = item,
                        Amount      = bundle.Amount[i],
                        Unit        = bundle.Unit[i],
                        IdRecipe    = data.Id
                    };

                    _context.RecipeDetails.Add(recipeDetail);

                    i++;
                }
            }

            await _context.SaveChangesAsync();

            var result = new GetCreateRecipe()
            {
                IdProduct  = data.IdProduct,
                NameRecipe = data.Name,
                Prioritize = data.Prioritize
            };

            return(new ApiSuccessResult <GetCreateRecipe>(result));
        }
コード例 #20
0
        public void UpdateRecipeShouldUpdateTheRecipe()
        {
            // Arrange

            var updateRecipe = new UpdateRecipe
            {
                Id    = "1",
                Title = "test"
            };

            autoMoqer.GetMock <IRecipeBookDataManager>().Setup(c => c.Recipes.UpdateItemAsync(It.IsAny <string>(), It.IsAny <RecipeEntry>())).Returns(Task.CompletedTask);

            // Act
            var response = recipeBookRequestHandler.Handle(updateRecipe, cancellationToken).Result;

            // Assert
            Assert.NotNull(response);
            Assert.IsType <RecipeEntry>(response);
            Assert.True(response.Title == updateRecipe.Title);
            autoMoqer.GetMock <IRecipeBookDataManager>().Verify(c => c.Recipes.UpdateItemAsync(It.Is <string>(x => x == updateRecipe.Id), It.IsAny <RecipeEntry>()), Times.Once);
        }
コード例 #21
0
        public async Task <RecipeEntry> Handle(UpdateRecipe request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Updating recipe", request);

            var recipe = await _recipeBookDataManager.Recipes.GetItemAsync(request.Id);

            if (recipe == null)
            {
                throw new MissingRecordException($"Recipe with id: {request.Id} not found");
            }

            if (recipe.OwnerId != _currentUser.UserId)
            {
                throw new RestrictedUpdateException("Cannot update recipe you don't own");
            }

            recipe = _mapper.MergeInto <RecipeEntry>(recipe, request);

            await _recipeBookDataManager.Recipes.UpdateItemAsync(recipe.Id, recipe);

            return(recipe);
        }
コード例 #22
0
        public async Task UpdateAsync(UpdateRecipe command, int id)
        {
            if (await _context.Recipes.ExistsInDatabaseAsync(id) == false)
            {
                throw new CorruptedOperationException("Recipe doesn't exist.");
            }

            var recipe = await GetAsync(id);

            recipe.Update(command.Name, command.Description, command.IsLactoseFree,
                          command.IsGlutenFree, command.IsVegan, command.IsVegetarian);

            _context.Components.RemoveRange(recipe.Components);
            recipe.Components.Clear();

            var components = CreateComponentsFromCommand(command.Components);
            await _context.Components.AddRangeAsync(components);

            recipe.Components = components;

            _context.Recipes.Update(recipe);
            await _context.SaveChangesAsync();
        }
コード例 #23
0
        public async void ShouldUpdateRecipeCorrectly()
        {
            // "051F13A0-4796-4B1C-9797-EC99F08CF25E" - sample recipe id to update
            var command = new UpdateRecipe
            {
                EntityId    = new Guid("051F13A0-4796-4B1C-9797-EC99F08CF25E"),
                Name        = "sample-name",
                Description = "sample-description",
                PictureUrl  = "https://example.com/sample-picture.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 UpdateRecipeHandler(eventStore.Object, MockBuilder.BuildFakeRecipeEventsMapper(), MockBuilder.BuildFakeCurrentUserService(), MockBuilder.BuildFakeDateTimeService());

            await handler.Handle(command, CancellationToken.None);

            var expected = new RecipeUpdated
            {
                EntityId    = new Guid("051F13A0-4796-4B1C-9797-EC99F08CF25E"),
                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-picture.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 <RecipeUpdated>(y => y.WithDeepEqual(expected).Compare())));
        }
コード例 #24
0
 public void UpdateStock(UpdateRecipe UpdateRecipe)
 {
     _RecipeRepo.UpdateStock(UpdateRecipe);
 }
コード例 #25
0
        public async Task <IActionResult> UpdatingRecipeAsync(int RecipeId, UpdateRecipe UpdateRecipe, string Content)
        {
            int? UserId = HttpContext.Session.GetInt32("UserId");
            User User   = dbContext.Users.FirstOrDefault(user => user.UserId == UserId);

            if (User != null)
            {
                AdminRecipe Recipe = dbContext.AdminRecipes.Include(recipe => recipe.User).FirstOrDefault(recipe => recipe.RecipeId == RecipeId);
                if (User.AdminState == 1)
                {
                    if (Request.Form["deletePicture"] == "on")
                    {
                        UpdateRecipe.UploadPicture = null;
                        Recipe.PictureURL          = null;
                    }
                    if (UpdateRecipe.UploadPicture != null)
                    {
                        var container              = Recipe.GetBlobContainer(configuration.GetSection("PictureBlobInfo:AzureStorageConnectionString").Value, "foodforumpictures");
                        var PictureContent         = ContentDispositionHeaderValue.Parse(UpdateRecipe.UploadPicture.ContentDisposition);
                        var FileName               = PictureContent.FileName.ToString().Trim('"');
                        var blockBlob              = container.GetBlockBlobReference(FileName);
                        BlobRequestOptions options = new BlobRequestOptions();
                        options.SingleBlobUploadThresholdInBytes = 16777216;
                        await blockBlob.UploadFromStreamAsync(UpdateRecipe.UploadPicture.OpenReadStream());

                        UpdateRecipe.PictureURL = blockBlob.Uri.AbsoluteUri;
                        if (UpdateRecipe.PictureURL != null && !dbContext.Recipes.Any(recipe => recipe.PictureURL == UpdateRecipe.PictureURL))
                        {
                            Recipe.PictureURL = UpdateRecipe.PictureURL;
                        }
                    }
                    Recipe.Title = UpdateRecipe.Title;
                    Recipe TitleCheck = dbContext.Recipes.FirstOrDefault(recipe => recipe.Title == Recipe.Title);
                    if (TitleCheck != null && TitleCheck.RecipeId != Recipe.RecipeId)
                    {
                        ViewBag.Recipe = Recipe;
                        ModelState.AddModelError("Title", "A recipe already has that title");
                        return(View("UpdateRecipe"));
                    }
                    Recipe.Note                 = UpdateRecipe.Note;
                    Recipe.Content              = Content;
                    Recipe.IngredientOne        = UpdateRecipe.IngredientOne;
                    Recipe.IngredientTwo        = UpdateRecipe.IngredientTwo;
                    Recipe.IngredientThree      = UpdateRecipe.IngredientThree;
                    Recipe.IngredientFour       = UpdateRecipe.IngredientFour;
                    Recipe.IngredientFive       = UpdateRecipe.IngredientFive;
                    Recipe.IngredientSix        = UpdateRecipe.IngredientSix;
                    Recipe.IngredientSeven      = UpdateRecipe.IngredientSeven;
                    Recipe.IngredientEight      = UpdateRecipe.IngredientEight;
                    Recipe.IngredientNine       = UpdateRecipe.IngredientNine;
                    Recipe.IngredientTen        = UpdateRecipe.IngredientTen;
                    Recipe.IngredientEleven     = UpdateRecipe.IngredientEleven;
                    Recipe.IngredientTwelve     = UpdateRecipe.IngredientTwelve;
                    Recipe.IngredientThirteen   = UpdateRecipe.IngredientThirteen;
                    Recipe.IngredientFourteen   = UpdateRecipe.IngredientFourteen;
                    Recipe.IngredientFifteen    = UpdateRecipe.IngredientFifteen;
                    Recipe.UpdatedAt            = UpdateRecipe.CreatedAt;
                    Recipe.User.ConfirmPassword = null;
                    TryValidateModel(Recipe);
                    ModelState.Remove("User.ConfirmPassword");
                    if (UpdateRecipe.PictureURL != null && dbContext.Recipes.Any(recipe => recipe.PictureURL == Recipe.PictureURL))
                    {
                        ModelState.AddModelError("UploadPicture", "A recipe already has a picture with that file name, please rename it and try again");
                    }
                    string check = RegexCheck(Recipe, RegEx);
                    if (check != null)
                    {
                        ModelState.AddModelError(check, "Please use only letters, numbers, periods, commas, hyphens, or exclamation points");
                    }
                    if (ModelState.IsValid)
                    {
                        dbContext.SaveChanges();
                        return(RedirectToAction("Index", "Home"));
                    }
                    ViewBag.Recipe = Recipe;
                    return(View("UpdateRecipe"));
                }
                return(RedirectToAction("Recipe", "Recipes", new { Title = Recipe.Title }));
            }
            return(RedirectToAction("Index", "Home"));
        }
コード例 #26
0
 public async Task <RecipeEntry> Put(string id, [FromBody] UpdateRecipe value)
 {
     return(await _mediator.Send(value));
 }
コード例 #27
0
        public async Task <RecipeToNotify> UpdateAsync(UpdateRecipe model, IValidator <UpdateRecipe> validator)
        {
            ValidateAndThrow(model, validator);

            string oldImageUri = await GetImageUriAsync(model.Id);

            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.ModifiedDate = now;

            Recipe original = await _recipesRepository.UpdateAsync(recipe, model.IngredientIdsToRemove);

            var result = _mapper.Map <RecipeToNotify>(original);

            // If the recipe image was changed
            if (oldImageUri != model.ImageUri)
            {
                // and it previously had one, delete it
                if (oldImageUri != null)
                {
                    await _cdnService.DeleteAsync(oldImageUri);
                }

                // and a new one was set, remove its temp tag
                if (model.ImageUri != null)
                {
                    await _cdnService.RemoveTempTagAsync(model.ImageUri);
                }
            }

            return(result);
        }
コード例 #28
0
 public void UpdateStock(UpdateRecipe UpdateRecipe)
 {
     //Dapper
 }
コード例 #29
0
 public static void MapToRecipe(this UpdateRecipe updateRecipe, Recipe recipe)
 {
     recipe.Name        = updateRecipe.RecipeName;
     recipe.Description = updateRecipe.Description;
     //map here other properties
 }
コード例 #30
0
        public async Task <IActionResult> Update(UpdateRecipe bundle)
        {
            var result = await _recipeApiClient.Update(bundle);

            return(Ok(result));
        }