예제 #1
0
        public ResponseViewModel CreateGallery(CreateGalleryViewModel model)
        {
            ResponseViewModel reponse = new ResponseViewModel();

            try
            {
                Galeria gallery = new Galeria
                {
                    IdEvento = model.IdEvento,
                    Image    = model.Image
                };
                _eventPlusContext.Galeria.Add(gallery);
                _eventPlusContext.SaveChanges();

                reponse.Type     = "success";
                reponse.Response = "El regitsro se creo exitosamente.";

                return(reponse);
            }
            catch (Exception ex)
            {
                reponse.Type     = "error";
                reponse.Response = "Error en el procedimiento. ---> " + ex.Message;
                return(reponse);
            }
        }
예제 #2
0
        public async Task <IActionResult> Create(int?id)
        {
            if (id == null)
            {
                return(View());
            }

            var product = await _context.Products.SingleOrDefaultAsync(d => d.ProductId == id);

            if (product == null)
            {
                ModelState.AddModelError("", DatabaseErrorMessage.ProductNotFound);
                return(View());
            }

            var model = new CreateGalleryViewModel()
            {
                Gallery = new Gallery()
                {
                    Name = product.Name + "_gallery"
                },
                ProductId = product.ProductId
            };

            return(View(model));
        }
        // GET: Galleries/Create
        public ActionResult Create(int?id)
        {
            if (id == null)
            {
                return(View());
            }

            var product = db.Products.SingleOrDefault(d => d.Id == id);

            if (product == null)
            {
                return(View());
            }

            var model = new CreateGalleryViewModel()
            {
                Gallery = new Gallery()
                {
                    Name = product.Name + "_gallery"
                },
                ProductId = product.Id
            };

            return(View(model));
        }
예제 #4
0
        public void Create_Post_Should_Add_Gallery_And_Redirect_To_Index()
        {
            // Arrange
            var viewModel = new CreateGalleryViewModel()
            {
                GalleryName = "NewGallery"
            };

            _imageGalleryServiceMock.Setup(o => o.CreateImageGallery("NewGallery")).Verifiable();

            // Act
            var result = _adminController.Create(viewModel);

            // Assert
            _imageGalleryServiceMock.Verify();
            result.AssertActionRedirect().ToAction("Index");
        }
예제 #5
0
        public async Task <IActionResult> Create(CreateGalleryViewModel model)
        {
            if (ModelState.IsValid)
            {
                _context.Add(model.Gallery);
                await _context.SaveChangesAsync();

                if (model.ProductId > 1)
                {
                    var product = await _context.Products.SingleOrDefaultAsync(d => d.ProductId == model.ProductId);

                    product.GalleryId = model.Gallery.GalleryId;
                }

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Edit), new { id = model.Gallery.GalleryId }));
            }
            return(View(model));
        }
        public ActionResult Create(CreateGalleryViewModel model)
        {
            if (ModelState.IsValid)
            {
                db.Galleries.Add(model.Gallery);
                db.SaveChanges();

                if (model.ProductId > 1)
                {
                    var product = db.Products.SingleOrDefault(d => d.Id == model.ProductId);
                    product.GalleryId = model.Gallery.Id;
                }

                db.SaveChanges();


                return(RedirectToAction("Edit", "Galleries", new { id = model.Gallery.Id }));
            }

            return(View(model));
        }
예제 #7
0
        public ActionResult Create(CreateGalleryViewModel addGalleryViewModel)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageImageGallery, T("Couldn't create image gallery")))
            {
                return(new HttpUnauthorizedResult());
            }
            if (!ModelState.IsValid)
            {
                return(View(addGalleryViewModel));
            }

            try {
                _imageGalleryService.CreateImageGallery(addGalleryViewModel.GalleryName);

                Services.Notifier.Information(T("Image gallery created"));
                return(RedirectToAction("Index"));
            }
            catch (Exception exception) {
                Services.Notifier.Error(T("Creating image gallery failed: {0}", exception.Message));
                return(View(addGalleryViewModel));
            }
        }
예제 #8
0
        public async Task <IActionResult> CreateGallery(CreateGalleryViewModel model, IFormFile sliderImage)
        {
            // Настройки галереи
            SettingsGallery settings = await _websiteDB.SettingsGallery.FirstAsync();

            int imageSize = 1048576 * settings.MaxImageSize;

            // Проверяем, чтобы обязательно был указан файл с изображением
            if (sliderImage == null || sliderImage.Length == 0)
            {
                ModelState.AddModelError("GallerySliderImage", "Укажите изображение для показа в слайдере.");
            }
            // Проверяем, чтобы входящий файл не превышал установленный максимальный размер
            if (sliderImage != null && sliderImage.Length > imageSize)
            {
                ModelState.AddModelError("GallerySliderImage", $"Файл \"{sliderImage.FileName}\" превышает установленный лимит 2MB.");
            }

            // Проверяем чтобы не случился дубликат имени галереи
            Gallery gallery = await _websiteDB.Galleries.FirstOrDefaultAsync(g => g.GalleryTitle == model.GalleryTitle);

            if (gallery != null)
            {
                ModelState.AddModelError("GalleryTitle", "Галерея с таким именем уже существует");
            }

            // Если на пути проблем не возникло, то создаем галерею
            if (ModelState.IsValid)
            {
                // Создаем новый объект класса FileInfo из полученного изображения для дальнейшей обработки
                FileInfo imgFile = new FileInfo(sliderImage.FileName);
                // Приводим расширение файла к нижнему регистру
                string imgExtension = imgFile.Extension.ToLower();
                // Генерируем новое имя для файла
                string newFileName = Guid.NewGuid() + imgExtension;
                // Пути сохранения файла
                string sliderDirectory = "/uploadedfiles/gallery/images/slider/";
                // Если такой директории не существует, то создаем её
                if (!Directory.Exists(_appEnvironment.WebRootPath + sliderDirectory))
                {
                    Directory.CreateDirectory(_appEnvironment.WebRootPath + sliderDirectory);
                }
                // Путь для слайд-изображения
                string pathSliderImage = sliderDirectory + newFileName;

                // В операторе try/catch делаем уменьшенную копию изображения.
                // Если входным файлом окажется не изображение, нас перекинет в блок CATCH и выведет сообщение об ошибке
                try
                {
                    // Создаем объект класса SixLabors.ImageSharp.Image и грузим в него полученное изображение
                    using (Image image = Image.Load(sliderImage.OpenReadStream()))
                    {
                        // Создаем уменьшенную копию и обрезаем её
                        var clone = image.Clone(x => x.Resize(new ResizeOptions
                        {
                            Mode = ResizeMode.Crop,
                            Size = new Size(1056, 220)
                        }));
                        // Сохраняем уменьшенную копию
                        await clone.SaveAsync(_appEnvironment.WebRootPath + pathSliderImage, new JpegEncoder { Quality = settings.ImageResizeQuality });
                    }
                }
                // Если вдруг что-то пошло не так (например, на вход подало не картинку), то выводим сообщение об ошибке
                catch
                {
                    // Создаем сообщение об ошибке для вывода пользователю
                    ModelState.AddModelError("GallerySliderImage", $"Файл {sliderImage.FileName} имеет неверный формат.");

                    // Возвращаем модель с сообщением об ошибке в представление
                    return(View(model));
                }

                if (string.IsNullOrEmpty(model.GalleryDescription))
                {
                    model.GalleryDescription = "";
                }

                gallery = new Gallery()
                {
                    Id                 = Guid.NewGuid(),
                    GalleryTitle       = model.GalleryTitle,
                    GalleryDescription = model.GalleryDescription.SpecSymbolsToView(),
                    GalleryDate        = DateTime.Now,
                    GalleryUserName    = User.Identity.Name,
                    GallerySliderImage = pathSliderImage
                };

                await _websiteDB.Galleries.AddAsync(gallery);

                await _websiteDB.SaveChangesAsync();

                return(RedirectToAction("Index", "Gallery"));
            }

            // Возврат модели при неудачной валидации
            return(View(model));
        }
예제 #9
0
        public IActionResult CreateGallery([FromBody] CreateGalleryViewModel model)
        {
            var user = _eventoService.CreateGallery(model);

            return(Ok(user));
        }