コード例 #1
0
        // Like implementation
        public ActionResult Like(int id)
        {
            var lists = from s in galleryService.LoadAll()
                        select s;

            GalleryDTO update = lists.Where(x => x.Id == id).FirstOrDefault();

            if (update.IsActive)
            {
                try
                {
                    if (update.post_like == null)
                    {
                        update.post_like = 0;
                    }
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine("The problem with id in GalleriesVM");
                }

                update.Id = id;
                update.post_like++;
                update.IsActive = false;
                galleryService.Save(update);
            }
            else
            {
                return(RedirectToAction("Index"));
            }
            return(RedirectToAction("Index"));
        }
コード例 #2
0
        public async Task <ActionResult <GalleryDTO> > PutGallery(Guid galleryId, GalleryPutDTO galleryPutDTO)
        {
            Guid userId = new Guid(HttpContext.User.Identity.Name);

            if (await _galleryService.DoesGalleryExistAsync(galleryId) == false)
            {
                return(NotFound());
            }

            if (await _galleryService.IsGalleryOwnedByUserAsync(galleryId, userId) == false)
            {
                return(Unauthorized());
            }

            try
            {
                GalleryDTO galleryDto = await _galleryService.PutGalleryAsync(userId, galleryId, galleryPutDTO);

                return(CreatedAtAction(nameof(GetGallery), new { id = galleryDto.Id }, galleryDto));
            }
            catch (Exception ex)
            {
                var problemDetails = new ProblemDetails
                {
                    Title    = "An unexpected error occurred.",
                    Status   = StatusCodes.Status500InternalServerError,
                    Detail   = "Unable to update the gallery at this moment due to an error, the error has been logged and sent to the developers for fixing.",
                    Instance = HttpContext.TraceIdentifier,
                };
                return(StatusCode(StatusCodes.Status500InternalServerError, problemDetails));
            }
        }
コード例 #3
0
        public async Task PutGallery_mine_and_it_exist()
        {
            // Arrange
            var controller = new GalleryController(GalleryService.Object);

            controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString());
            GalleryEntity newGalleryEntity = new GalleryEntity()
            {
                Id       = Guid.NewGuid(),
                Name     = "TestGalleryName",
                fk_owner = UserEntities[0].Id,
                owner    = UserEntities[0]
            };

            GalleryEntities.Add(newGalleryEntity);

            // Act
            GalleryPutDTO             galleryPutDto = new GalleryPutDTO("UpdatedTestGalleryName");
            ActionResult <GalleryDTO> response      = await controller.PutGallery(newGalleryEntity.Id, galleryPutDto);

            // Assert
            Assert.IsInstanceOfType(response.Result, typeof(CreatedAtActionResult));
            var result = response.Result as CreatedAtActionResult;

            Assert.AreEqual(201, result.StatusCode);
            Assert.IsNotNull(result.Value);
            Assert.IsInstanceOfType(result.Value, typeof(GalleryDTO));
            GalleryDTO retrievedItem = result.Value as GalleryDTO;

            Assert.AreEqual(retrievedItem.Id, newGalleryEntity.Id);
            Assert.AreEqual(retrievedItem.Name, "UpdatedTestGalleryName");
            GalleryEntities.Remove(newGalleryEntity);
        }
コード例 #4
0
        public async ValueTask <(bool isSuccess, string error)> AddGallery(GalleryDTO entityDTO)
        {
            var gallery = new Gallery()
            {
                Alias          = entityDTO.Alias,
                NormalizeAlias = entityDTO.Alias.TransformToId(),
                IsVisible      = entityDTO.IsVisible ?? true,

                Photos = new List <Photo>()
            };

            //Добавляем и проверяем можем ли мы добавить данную категорию
            var(isSuccess, error) = await _repository.AddGallery(gallery);

            if (!isSuccess)
            {
                return(isSuccess, error);
            }

            await _photoEntityUpdater.LoadPhotosToEntity(gallery, entityDTO, maxPixel : 1600);

            await _context.SaveChangesAsync();

            return(true, null);
        }
コード例 #5
0
 public GalleryVM(GalleryDTO row)
 {
     Id        = row.Id;
     ProductId = row.ProductId;
     Img       = row.Img;
     ImgType   = row.ImgType;
 }
コード例 #6
0
        public void Delete(GalleryDTO coachDTO)
        {
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap <Galleries, GalleryDTO>()).CreateMapper();
            var coach  = mapper.Map <Galleries>(coachDTO);

            unitOfWork.Galleries.Delete(coach.Id);
            unitOfWork.Galleries.Save();
        }
コード例 #7
0
 public void DeleteImg(int id)
 {
     using (Db db = new Db())
     {
         GalleryDTO dto = db.ProductGallery.Find(id);
         db.ProductGallery.Remove(dto);
         db.SaveChanges();
     }
 }
コード例 #8
0
        public List <GalleryDTO> GetListPage(int currentPage, int pageSize, GalleryCondition condition = null)
        {
            IEnumerable <Gallery> galleries = _galleryRepository.SelectByPage(currentPage, pageSize);
            List <GalleryDTO>     list      = new List <GalleryDTO>();

            foreach (var item in galleries)
            {
                GalleryDTO galleryDTO = new GalleryDTO();
                galleryDTO.Url = item.Url;
                list.Add(galleryDTO);
            }
            return(list);
        }
コード例 #9
0
        public async Task <IActionResult> AddOrUpdate([FromForm] GalleryDTO galleryDTO)
        {
            const string API_LOCATE = CONTROLLER_LOCATE + ".AddOrUpdate";
            var          error      = ERROR;

            try
            {
                bool isSuccess;

                if (galleryDTO.GalleryId <= 0)
                {
                    (isSuccess, error) = await _service.AddGallery(galleryDTO);
                }
                else
                {
                    var oldGallery = await _repository.GetGallery(galleryDTO.GalleryId);

                    if (oldGallery is null)
                    {
                        return(LogBadRequest(
                                   _logger,
                                   API_LOCATE,
                                   customError: $"Что-то пошло не так, не удалось найти галерею.\n\tГалерея: {galleryDTO.GalleryId}"
                                   ));
                    }

                    (isSuccess, error) = await _service.UpdateGallery(galleryDTO, oldGallery);
                }

                if (!isSuccess)
                {
                    return(LogBadRequest(
                               _logger,
                               API_LOCATE,
                               customError: error
                               ));
                }

                return(Success(isSuccess));
            }
            catch (Exception ex)
            {
                return(LogBadRequest(
                           _logger,
                           API_LOCATE,
                           exception: ex,
                           customError: error
                           ));
            }
        }
コード例 #10
0
        public void Save(GalleryDTO coachesDTO)
        {
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap <Galleries, GalleryDTO>()).CreateMapper();
            var coach  = mapper.Map <Galleries>(coachesDTO);

            if (coachesDTO.Id == 0)
            {
                Add(coach); // попробывать описать по отдельности по стандарту добавление и обновление данные. Для этого ADDED и Updated нужно расписать.
            }
            else
            {
                Update(coach);
            }
            unitOfWork.Galleries.Save();
        }
コード例 #11
0
        //for gallery image
        public FileContentResult GetGallery(int id)
        {
            using (Db db = new Db())
            {
                GalleryDTO img = db.ProductGallery.Find(id);

                if (img != null)
                {
                    return(File(img.Img, img.ImgType));
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #12
0
        public ActionResult AddImage()
        {
            // Checking no of files injected in Request object
            if (Request.Files.Count > 0)
            {
                try
                {
                    //  Get all files from Request object
                    HttpFileCollectionBase files = Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];

                        // get file name
                        DateTime date  = DateTime.UtcNow;
                        string   fname = "image-"
                                         + date.ToShortDateString().Replace('/', '-')
                                         + "-"
                                         + date.ToLongTimeString().Replace(':', ' ')
                                         + Path.GetExtension(file.FileName);

                        // Get the complete folder path and store the file inside it.
                        var imgPath = Path.Combine(Server.MapPath("~/Content/assets/img/gallery/"), fname);
                        file.SaveAs(imgPath);

                        // save record
                        var galleryRecord = new GalleryDTO {
                            ImageUrl = "/Content/assets/img/gallery/" + fname
                        };
                        db.Gallery.Add(galleryRecord);
                        db.SaveChanges();
                    }

                    // Returns message that successfully uploaded
                    return(Json("File Uploaded Successfully!"));
                }
                catch (Exception ex)
                {
                    return(Json("Error occurred. Error details: " + ex.Message));
                }
            }
            else
            {
                return(Json("No files selected."));
            }
        }
コード例 #13
0
        public async Task <GalleryDTO> PutGalleryAsync(Guid userId, Guid galleryId, GalleryPutDTO galleryPutDTO)
        {
            GalleryEntity galleryEntity = await _galleryRepository.GetGallery(galleryId);

            galleryPutDTO.ToGalleryEntity(ref galleryEntity);

            await _galleryRepository.PutGallery(galleryEntity);

            if (_galleryRepository.Save() == false)
            {
                throw new Exception();
            }

            int        numImagesInGallery = _imageRepository.GetNumberOfImagesInGallery(galleryEntity.Id);
            GalleryDTO dtoToReturn        = galleryEntity.ToGalleryDto(numImagesInGallery);

            return(dtoToReturn);
        }
コード例 #14
0
        public async Task <ActionResult <GalleryDTO> > GetGallery(Guid id)
        {
            Guid userId = new Guid(HttpContext.User.Identity.Name);

            if (await _galleryService.DoesGalleryExistAsync(id) == false)
            {
                return(NotFound());
            }

            if (await _galleryService.IsGalleryOwnedByUserAsync(id, userId) == false)
            {
                return(Unauthorized());
            }

            GalleryDTO dto = await _galleryService.GetGalleryAsync(id);

            return(Ok(dto));
        }
コード例 #15
0
ファイル: GalleryController.cs プロジェクト: t00ks/TooksCms
        public HttpResponseMessage Put(GalleryDTO gallery)
        {
            try
            {
                var model = new GalleryModel(gallery);

                if (model.Id > 0)
                {
                    model.MarkOld(); model.MarkDirty();
                }
                model.Save();

                return(Request.CreateResponse(HttpStatusCode.NoContent));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
コード例 #16
0
        public void Upload(GalleryDTO galleryDTO)
        {
            if (string.IsNullOrEmpty(galleryDTO.Account))
            {
                throw new ArgumentException("account为空");
            }
            if (string.IsNullOrEmpty(galleryDTO.Url))
            {
                throw new ArgumentException("url为空");
            }
            Gallery gallery = new Gallery();

            gallery.Account     = galleryDTO.Account;
            gallery.Url         = galleryDTO.Url;
            gallery.Lable       = galleryDTO.Lable;
            gallery.Description = galleryDTO.Description;
            gallery.CreateTime  = DateTime.Now;
            _galleryRepository.Insert(gallery);
        }
コード例 #17
0
        public async ValueTask <(bool isSuccess, string error)> UpdateGallery(GalleryDTO galleryDTO, Gallery oldGallery)
        {
            if (oldGallery.NormalizeAlias != galleryDTO.Alias.TransformToId())
            {
                var entity = await _repository.GetGallery(galleryDTO.Alias);

                if (entity != null)
                {
                    return(false, "Галерея с таким наименованием уже существует");
                }
            }

            await _photoEntityUpdater.LoadPhotosToEntity(oldGallery, galleryDTO, maxPixel : 1600);

            oldGallery.Alias          = galleryDTO.Alias;
            oldGallery.NormalizeAlias = galleryDTO.Alias.TransformToId();
            oldGallery.IsVisible      = galleryDTO.IsVisible ?? true;

            return(await _repository.UpdateGallery(oldGallery));
        }
コード例 #18
0
        public ActionResult Like(int id)
        {
            GalleryDTO update = galleryService.Load(id);             // must be changed

            try
            {
                if (update.post_like == null)
                {
                    update.post_like = 0;
                }
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("The problem with id in GalleriesVM");
            }

            update.Id         = id;
            update.post_like += 1;
            galleryService.Save(update);                                                           // must be changed
            return(RedirectToAction("Index"));
        }
コード例 #19
0
        public void SaveGallaryImages(int id) //не работает при создании товара т.к. у товора до создания нету ИД
        {
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];

                if (file != null && file.ContentLength > 0)
                {
                    using (Db db = new Db())
                    {
                        GalleryDTO dto = new GalleryDTO();
                        dto.ProductId = id;
                        dto.ImgType   = file.ContentType;
                        dto.Img       = new byte[file.ContentLength];
                        file.InputStream.Read(dto.Img, 0, file.ContentLength);

                        db.ProductGallery.Add(dto);
                        db.SaveChanges();
                    }
                }
            }
        }
コード例 #20
0
        public async Task <ActionResult <GalleryDTO> > CreateGallery(GalleryCreationDTO creationDto)
        {
            Guid userId = new Guid(HttpContext.User.Identity.Name);

            try
            {
                GalleryDTO dto = await _galleryService.CreateGalleryAsync(userId, creationDto);

                return(CreatedAtAction(nameof(GetGallery), new { id = dto.Id }, dto));
            }
            catch (Exception ex)
            {
                var problemDetails = new ProblemDetails
                {
                    Title    = "An unexpected error occurred.",
                    Status   = StatusCodes.Status500InternalServerError,
                    Detail   = "Unable to create the gallery at this moment due to an error, the error has been logged and sent to the developers for fixing.",
                    Instance = HttpContext.TraceIdentifier,
                };
                return(StatusCode(StatusCodes.Status500InternalServerError, problemDetails));
            }
        }
コード例 #21
0
        public async Task CreateGallery()
        {
            // Arrange
            var controller = new GalleryController(GalleryService.Object);

            controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[1].Id.ToString());

            GalleryCreationDTO newGalleryItem = new GalleryCreationDTO("CreatedTestName");

            // Act
            ActionResult <GalleryDTO> response = await controller.CreateGallery(newGalleryItem);

            // Assert
            Assert.IsInstanceOfType(response.Result, typeof(CreatedAtActionResult));
            var result = response.Result as CreatedAtActionResult;

            Assert.AreEqual(201, result.StatusCode);
            Assert.IsNotNull(result.Value);
            Assert.IsInstanceOfType(result.Value, typeof(GalleryDTO));
            GalleryDTO createdItem = result.Value as GalleryDTO;

            Assert.AreEqual(createdItem.Name, "CreatedTestName");
        }
コード例 #22
0
        public async Task GetGallery_mine_and_it_exist()
        {
            // Arrange
            var controller = new GalleryController(GalleryService.Object);
            var retrieveThisGalleryItem = GalleryEntities[0];

            controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString());

            // Act
            ActionResult <GalleryDTO> response = await controller.GetGallery(retrieveThisGalleryItem.Id);

            // Assert
            Assert.IsInstanceOfType(response.Result, typeof(OkObjectResult));
            var result = response.Result as OkObjectResult;

            Assert.AreEqual(200, result.StatusCode);
            Assert.IsNotNull(result.Value);
            Assert.IsInstanceOfType(result.Value, typeof(GalleryDTO));
            GalleryDTO retrievedItem = result.Value as GalleryDTO;

            Assert.AreEqual(retrieveThisGalleryItem.Id, retrievedItem.Id);
            Assert.AreEqual(retrieveThisGalleryItem.Name, retrievedItem.Name);
        }
コード例 #23
0
 public ApiResult Upload([FromBody] GalleryDTO galleryDTO)
 {
     _galleryService.Upload(galleryDTO);
     return(ApiResult.Success());
 }