Пример #1
0
        public async Task UpdateAsync(int id, PhotoDTO item)
        {
            var photo = mapper.Map <Photo>(item);

            photo.Id = id;
            await unitOfWork.Photos.UpdateAsync(photo);
        }
Пример #2
0
        public async Task <JsonResult> Upload(HttpPostedFileBase[] files)
        {
            var adId  = (int)Session[Resources.AdvertsmentId];
            var first = !await this.advertismentService.HasFirstPhoto(adId);

            foreach (var file in files)
            {
                var photoId    = Guid.NewGuid();
                var fileS3Name = $"{adId}/{photoId + Path.GetExtension(file.FileName)}";
                var photo      = new PhotoDTO
                {
                    Id    = photoId,
                    AdvId = adId,
                    Url   = $"{Resources.AmazonUrl}/{this.cloudService.BucketName}/{fileS3Name}",
                    First = first
                };
                first = false;
                await this.advertismentService.CreatePhotoAsync(photo);

                await this.cloudService.UploadFromStream(fileS3Name, file.InputStream);
            }

            Session[Resources.AdvertsmentId] = null;
            return(new JsonResult()
            {
                Data = new { result = true }
            });
        }
Пример #3
0
        public async Task <IActionResult> UploadPhoto(int userId, [FromForm] PhotoDTO photo)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var accountFromDb = await _repo.GetOneWithConditions <LuyenThiOnline.Models.Account>(account => account.Id == userId);

            var file         = photo.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var fileStream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, fileStream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            accountFromDb.PhotoUrl = uploadResult.Url.ToString();
            accountFromDb.PublicId = uploadResult.PublicId;
            if (await _repo.SaveAll())
            {
                return(Ok(new
                {
                    photoUrl = accountFromDb.PhotoUrl
                }));
            }
            return(BadRequest("Error on uploading photo"));
        }
Пример #4
0
        public ActionResult Upload(IEnumerable <HttpPostedFileBase> fileUploadMulti)//fileUploadMulti обязательно совпадет с input
        {
            string idstr = Request.Params["id"];
            int    id    = Convert.ToInt32(idstr);

            foreach (var file in fileUploadMulti)
            {
                if (file == null)
                {
                    continue;
                }
                string path        = AppDomain.CurrentDomain.BaseDirectory + "img/";
                string filename    = Path.GetFileName(file.FileName);
                string newfilename = Guid.NewGuid().ToString() + Path.GetExtension(filename);
                if (filename != null)
                {
                    file.SaveAs(Path.Combine(path, newfilename));
                    PhotoDTO photo = new PhotoDTO
                    {
                        ProductId = id,
                        PhotoPath = "/img/" + newfilename
                    };
                    servicePhoto.Add(photo);
                }
            }
            return(RedirectToAction("Index", new { id = id }));
        }
Пример #5
0
        public void UpdatePhoto(PhotoDTO photoDTO)
        {
            Photo photo = mapperDTOToEntity.Map <PhotoDTO, Photo>(photoDTO);

            Database.Photos.Update(photo);
            SaveChangesInDatabase();
        }
Пример #6
0
        public async Task <IActionResult> UserPhotoUpload(int Id, [FromForm] PhotoCloudinaryDTO photoCloudinary)
        {
            if (photoCloudinary.File == null)
            {
                return(BadRequest("File Not Exist!"));
            }

            if (Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            User user = await _repo.GetUser(Id);

            //upload in cloudinary
            var uploaResult = this.CloudinaryUpload(photoCloudinary.File);

            Photo photo = _mapper.Map <Photo>(photoCloudinary);

            photo.UserId   = user.Id;
            photo.Url      = uploaResult.Uri.ToString();
            photo.PublicId = uploaResult.PublicId;
            if (!user.Photos.Any())
            {
                photo.IsMain = true;
            }

            _repo.Add <Photo>(ref photo);
            if (await _repo.SaveChanges())
            {
                PhotoDTO photoDTO = _mapper.Map <PhotoDTO>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoDTO));
            }
            return(BadRequest("Could not add a photo"));
        }
Пример #7
0
        public async Task <IActionResult> UploadPhoto(int accountId, [FromForm] PhotoDTO photo)
        {
            if (accountId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var account = await _repo.GetAccountDetail(accountId);

            if (account.PublicId != null)
            {
                await DeletePhoto(account);
            }
            var result = _cloud.UploadImage(photo.File);

            account.PhotoUrl = result.PublicUrl;
            account.PublicId = result.PublicId;
            if (await _repo.SaveAll())
            {
                return(Ok(new
                {
                    photoUrl = account.PhotoUrl
                }));
            }
            return(BadRequest("Error on upload photo"));
        }
Пример #8
0
        /// <summary>
        /// Maps photo DTO to photo view model.
        /// </summary>
        public static PhotoViewModel ToViewModel(this PhotoDTO item)
        {
            if (item == null)
            {
                return(null);
            }

            return(new PhotoViewModel
            {
                Id = item.Id,
                Path = item.Path,
                Filter = item.Filter,
                Description = item.Description,
                Date = item.Date.ToString("MMMM dd, yyyy"),
                Owner = item.Owner.ToViewModel(),
                CountViews = item.CountViews,

                Liked = item.Liked,
                Bookmarked = item.Bookmarked,

                Manufacturer = string.IsNullOrEmpty(item.Manufacturer) ? "Unknown" : item.Manufacturer,
                Model = string.IsNullOrEmpty(item.Model) ? "Unknown" : item.Model,
                Iso = item.Iso != null?item.Iso.ToString() : "Unknown",
                          Exposure = item.Exposure != null ? $"{string.Format("{0:0.00000}", item.Exposure)} sec" : "Unknown",
                          Aperture = item.Aperture != null ? $"f/{item.Aperture.ToString()}" : "Unknown",
                          FocalLength = item.FocalLength != null ? $"{item.FocalLength.ToString()}mm" : "Unknown",

                          Likes = item.Likes.ToViewModels(),
                          Comments = item.Comments.ToViewModels(),
                          Tags = item.Tags.ToViewModels()
            });
        }
Пример #9
0
        public async Task UpdateAsync(PhotoDTO photoDTO)
        {
            Photo photoToUpd
                = mapper.Map <Photo>(photoDTO);

            await db.PhotoRepo.UpdateAsync(photoToUpd);
        }
Пример #10
0
        public async Task <IActionResult> UpdateAvatar(int accountId, [FromForm] PhotoDTO photoDTO)
        {
            int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (userId != accountId)
            {
                return(Unauthorized());
            }
            var accountFromDb = await _repo.GetAccountDetail(accountId);

            if (accountFromDb == null)
            {
                return(NotFound());
            }
            if (!string.IsNullOrEmpty(accountFromDb.PublicId))
            {
                _cloud.DeleteImage(accountFromDb.PublicId);
            }
            var result = _cloud.UploadImage(photoDTO.File);

            accountFromDb.PhotoUrl = result.PublicUrl;
            accountFromDb.PublicId = result.PublicId;
            if (await _repo.SaveAll())
            {
                return(Ok());
            }
            return(StatusCode(500));
        }
Пример #11
0
        public IActionResult GetPhotoAndComments(int id)
        {
            Photo photo = _dbContext.Photos.Include(p => p.RelatedComments).FirstOrDefault(p => p.PhotoId == id);

            if (photo != null)
            {
                // A data transfer object (DTO) has to be constructed to prevent from json serialization circular reference issue.
                PhotoDTO pd = new PhotoDTO
                {
                    PhotoId         = photo.PhotoId,
                    Title           = photo.Title,
                    FileName        = photo.FileName,
                    ImageMimeType   = photo.ImageMimeType,
                    Description     = photo.Description,
                    UserName        = photo.UserName,
                    CreatedDate     = photo.CreatedDate,
                    ModifiedDate    = photo.ModifiedDate,
                    RelatedComments = photo.RelatedComments.Select(c => new CommentDTO
                    {
                        CommentId   = c.CommentId,
                        PhotoId     = c.PhotoId,
                        UserName    = c.UserName,
                        Body        = c.Body,
                        CreatedDate = c.CreatedDate
                    }).ToList()
                };
                return(Ok(pd));
            }
            else
            {
                return(NotFound());
            }
        }
Пример #12
0
        public async Task CreatePhotoAsync(PhotoDTO newPhotoDTO)
        {
            Photo newPhoto = mapper.Map <Photo>(newPhotoDTO);
            await db.PhotoRepo.CreateAsync(newPhoto);

            await db.CommitAsync();
        }
Пример #13
0
        public ActionResult Upload(int id, IEnumerable <HttpPostedFileBase> fileUpload)
        {
            //string idstr = Request.Params["id"];
            //int id = Convert.ToInt32(idstr);
            foreach (var file in fileUpload)
            {
                if (file == null)
                {
                    continue;
                }
                string path     = AppDomain.CurrentDomain.BaseDirectory + "Files/";
                string filename = Path.GetFileName(file.FileName);

                if (filename != null)
                {
                    //1. Получаем расширение
                    string ext = Path.GetExtension(filename);
                    //2. Генерируем уникальный ключ...
                    var partname = Guid.NewGuid().ToString() + ext;
                    file.SaveAs(Path.Combine(path, partname));
                    PhotoDTO photo = new PhotoDTO
                    {
                        GoodId    = id,
                        PhotoPath = "/Files/" + partname
                    };
                    photoService.Add(photo);
                }
            }

            return(RedirectToAction("PhotoList", new { id = id }));
        }
Пример #14
0
 public ActionResult Create(PhotoDetailViewModel photoDetailViewModel, HttpPostedFileBase file)
 {
     if (ModelState.IsValid)
     {
         PhotoDTO photoDto  = Mapper.Map <PhotoDTO>(photoDetailViewModel);
         byte[]   imageData = null;
         if (file != null)
         {
             if (file.ContentLength > (500 * 1024))
             {
                 ModelState.AddModelError("ImageUploadValidationError", "File size must be less than 500 Kb");
                 return(View(photoDetailViewModel));
             }
             if (!file.IsJpgImage())
             {
                 ModelState.AddModelError("ImageUploadValidationError", "File type allowed : jpeg");
                 return(View(photoDetailViewModel));
             }
             photoDto.ImageId       = _imageServices.SaveImageToDb(file.InputStream, Enums.ImageSize.Actual);
             photoDto.SmallImageId  = _imageServices.SaveImageToDb(file.InputStream, Enums.ImageSize.Small);
             photoDto.MiddleImageId = _imageServices.SaveImageToDb(file.InputStream, Enums.ImageSize.Middle);
             photoDto.Created       = DateTime.Now;
         }
         _photoServices.CreatePhoto(photoDto);
         return(RedirectToAction("Index"));
     }
     return(View(photoDetailViewModel));
 }
Пример #15
0
        // GET: Admin/Shop/DeleteProduct/id
        public ActionResult DeleteProduct(int id)
        {
            string product = "";

            // Delete product from DB
            using (TicketAppDB db = new TicketAppDB())
            {
                ProductDTO dto = db.Products.Find(id);
                PdfDTO     pdf = db.Pdfs.Where(x => x.ProductId == id).FirstOrDefault();
                product = dto.Name;
                PhotoDTO photo = db.Photos.Where(x => x.ProductId == id).FirstOrDefault();
                //Determine if product is an order
                if (db.OrderDetails.Any(x => x.ProductId == id))
                {
                    OrderDetailsDTO dte = db.OrderDetails.Where(x => x.ProductId == id).FirstOrDefault();
                    OrderDTO        ord = db.Orders.Where(x => x.OrderId == dte.OrderId).FirstOrDefault();
                    db.OrderDetails.Remove(dte);
                    db.Orders.Remove(ord);
                }
                db.Pdfs.Remove(pdf);
                db.Photos.Remove(photo);
                db.Products.Remove(dto);

                db.SaveChanges();
            }

            TempData["SM"] = "You have deleted '" + product + "'!";
            // Redirect
            return(RedirectToAction("Products", "Shop"));
        }
Пример #16
0
        public CreateShould()
        {
            fixture = new SetupFixture();

            env = new Mock <IHostEnvironment>();
            imageUploadWrapper = new Mock <IImageUploadWrapper>();
            env.Setup(m => m.EnvironmentName).Returns("Hosting:UnitTestEnvironment");
            sut = new PhotoController(fixture.Logger.Object,
                                      fixture.repositoryWrapper.Object,
                                      fixture.mapper.Object,
                                      env.Object,
                                      imageUploadWrapper.Object);

            photo = new Photo()
            {
                Id = 1, ImageLink = "dgfdfgdf"
            };
            photoDTO = new PhotoDTO()
            {
                Id = 1, ImageLink = string.Empty, File = It.IsAny <IFormFile>()
            };


            fixture.repositoryWrapper
            .Setup(x => x.Photo.GetPhotoByIdAsync(It.IsAny <int>()))
            .ReturnsAsync(It.IsAny <Photo>);
            fixture.repositoryWrapper.Setup(x => x.Photo.GetAllPhotosAsync()).ReturnsAsync(new List <Photo>()
            {
                photo
            });
            fixture.mapper.Setup(x => x.Map <PhotoDTO>(It.IsAny <Photo>())).Returns(new PhotoDTO());
            imageUploadWrapper.Setup(x => x.Upload(It.IsAny <IFormFile>(), It.IsAny <IHostEnvironment>()))
            .Returns("imageurl");
        }
Пример #17
0
        public void AddPhoto(string albumName, PhotoDTO photo, string fileName)
        {
            Photo newPhoto = new Photo {
                Description = photo.Description,
                Path        = fileName,
                Rating      = photo.Rating,
                Title       = photo.Title,
                //InAlbum = _service.GetAlbumByName(albumName)
            };
            Album        album     = GetAlbumByName(albumName);
            List <Photo> photoList = album.Photos;

            if (photoList != null)
            {
                photoList.Add(newPhoto);
            }
            else
            {
                photoList = new List <Photo> {
                    newPhoto
                };
            }
            album.Photos = photoList;
            _repo.Add <Photo>(newPhoto);
            _repo.SaveChanges();
        }
Пример #18
0
        public async Task OnGetAsync()
        {
            var media = await fc.Afisare_MediaAsync();

            Campuri = await fc.Initializare_proprietatiAsync();

            if (!string.IsNullOrEmpty(Cauta))
            {
                media.Clear();
                string p1, p2;
                p1    = Camp;
                p2    = Cauta;
                media = await fc.Afisare_rezultateAsync(Camp, p2);
            }

            media.Sort();
            int i = 0;

            foreach (var item in media)
            {
                var p = new PhotoDTO();
                p.Path = item;
                p.Id   = i;
                i     += 1;
                Photos.Add(p);
            }
        }
Пример #19
0
        public async Task <ActionResult> DownloadImage(
            IFormFile file,
            [FromForm] string userName)
        {
            long size = file.Length;

            var filePath = Path.GetTempFileName();

            var upload   = Path.Combine(environment.WebRootPath, "images");
            var fullPath = Path.Combine(upload, GetUniqueName(file.FileName));

            file.CopyTo(new FileStream(fullPath, FileMode.Create));
            UserDTO user = (await userService.AllUsersAsync())
                           .Where(u => u.UserName == userName)
                           .FirstOrDefault();
            PhotoDTO newPhoto = new PhotoDTO()
            {
                ImageLink = fullPath,
                User      = user,
            };
            await photoService.CreatePhotoAsync(newPhoto);

            PhotoDTO photo = photoService
                             .AllPhotosAsync()
                             .Result
                             .Where(p => p.ImageLink == newPhoto.ImageLink)
                             .FirstOrDefault();

            string uri = "https://localhost:44390/api/photo/get/" + photo.Id;

            return(Created(uri, photo));
        }
Пример #20
0
        public async Task <IActionResult> UploadPhotoAsync(int vehicleId, IFormFile file)
        {
            var vehicle = vehicleService.GetVehicleAsync(vehicleId);

            if (vehicle == null)
            {
                return(NotFound());
            }

            if (file == null)
            {
                return(BadRequest("File is null"));
            }

            if (file.Length == 0)
            {
                return(BadRequest("Empty file"));
            }

            if (file.Length > photoSettings.MaxBytes)
            {
                return(BadRequest("Max file size exceeded"));
            }

            if (!photoSettings.IsSupportedFile(file.FileName))
            {
                return(BadRequest("Invalid file type"));
            }

            if (string.IsNullOrWhiteSpace(webHostEnvironment.WebRootPath))
            {
                webHostEnvironment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            }

            string uploadsFolderPath = Path.Combine(webHostEnvironment.WebRootPath, "images");

            if (!Directory.Exists(uploadsFolderPath))
            {
                Directory.CreateDirectory(uploadsFolderPath);
            }

            string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            string filePath = Path.Combine(uploadsFolderPath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            var photo = new PhotoDTO
            {
                FileName  = fileName,
                VehicleId = vehicle.Id
            };

            await photoService.CreateAsync(photo);

            return(Ok());
        }
Пример #21
0
        public async Task <IActionResult> GetPhoto(int Id)
        {
            Photo photo = await _repo.Get <Photo>(x => x.Id == Id);

            PhotoDTO photoDTO = _mapper.Map <PhotoDTO>(photo);

            return(Ok(photoDTO));
        }
Пример #22
0
        public async Task <IActionResult> AddPhoto(PhotoDTO photoDTO)
        {
            var requestDTO = _mapper.Map <PhotoDTO>(photoDTO);

            var addedRequest = await _service.AddPhoto(requestDTO);

            return(Ok(_mapper.Map <PhotoDTO>(addedRequest)));
        }
Пример #23
0
        public async Task <IActionResult> UpdatePhoto(PhotoDTO photoDTO)
        {
            var photo = _mapper.Map <PhotoDTO>(photoDTO);

            var editedPhoto = await _service.EditVisability(photoDTO);

            return(Ok(_mapper.Map <PhotoDTO>(editedPhoto)));
        }
Пример #24
0
 public void UpdatePhoto(PhotoDTO photoDto)
 {
     using (UnitOfWork unitOfWork = new UnitOfWork(new PhotoManagerDbContext()))
     {
         Photo photo = Mapper.Map <Photo>(photoDto);
         unitOfWork.Photos.UpdatePhoto(photo);
         unitOfWork.Complete();
     }
 }
Пример #25
0
 /// <summary>Adds the like.</summary>
 /// <param name="photo">The photo.</param>
 public void AddLike(PhotoDTO photo)
 {
     Database.Likes.Create(new Like
     {
         ProfileId = photo.ProfileId,
         PhotoId   = photo.PhotoId
     });
     var like = Database.Likes.GetAll().OrderByDescending(l => l.LikeId).FirstOrDefault(l => l.PhotoId == photo.PhotoId);
 }
Пример #26
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoDTO photoDTO)
        {
            var user = await _repo.GetUser(userId);

            if (user == null)
            {
                return(BadRequest("Could not find"));
            }

            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != user.Id)
            {
                return(Unauthorized());
            }

            var file = photoDTO.File;

            var uplodaRes = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uplodaRes = _cloudinary.Upload(uploadParams);
                }
            }

            photoDTO.Url      = uplodaRes.Uri.ToString();
            photoDTO.PublicId = uplodaRes.PublicId;

            var photo = _mapper.Map <Photo>(photoDTO);

            photo.User = user;

            if (!user.Photos.Any(po => po.IsMainPhoto))
            {
                photo.IsMainPhoto = true;
            }

            user.Photos.Add(photo);


            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturn>(photo);

                return(Ok(photoToReturn));
            }
            return(BadRequest("CDNT add the photo"));
        }
Пример #27
0
        public PhotoDTO Edit(int id, PhotoDTO entity)
        {
            _context.Entry(_context.Photos.FirstOrDefault(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var photo    = _context.Photos.Find(id);
            var photoDto = _mapper.Map <PhotoDTO>(photo);

            return(photoDto);
        }
Пример #28
0
 public IActionResult PostPic([FromBody] PhotoDTO pic)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     _pService.AddPhoto(pic);
     return(Ok());
 }
Пример #29
0
 public void CreatePhoto(PhotoDTO photoDto)
 {
     using (UnitOfWork unitOfWork = new UnitOfWork(new PhotoManagerDbContext()))
     {
         Photo photo = Mapper.Map <Photo>(photoDto);
         photo.UserId = WebSecurityService.GetCurrentUserId();
         unitOfWork.Photos.Add(photo);
         unitOfWork.Complete();
     }
 }
Пример #30
0
        public async Task <PhotoDTO> EditAsync(int id, PhotoDTO entity)
        {
            _context.Entry(await _context.Photos.FirstOrDefaultAsync(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var photo = await _context.Photos.FindAsync(id);

            var photoDto = _mapper.Map <PhotoDTO>(photo);

            return(photoDto);
        }