コード例 #1
0
        public Task <List <PhotoDto> > GetPhoto()
        {
            List <PhotoDto> listPhoto = new List <PhotoDto>();

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("usp_GetPhoto", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    PhotoDto objUserPhoto = new PhotoDto();
                    objUserPhoto.Id          = Convert.ToInt32(rdr["Id"]);
                    objUserPhoto.url         = Convert.ToString(rdr["Url"]);
                    objUserPhoto.Description = Convert.ToString(rdr["Description"]);
                    objUserPhoto.AddDate     = Convert.ToDateTime(rdr["AddDate"]);
                    objUserPhoto.IsMain      = Convert.ToBoolean(rdr["IsMain"]);
                    objUserPhoto.PublicId    = Convert.ToString(rdr["PublicId"]);

                    listPhoto.Add(objUserPhoto);
                }
                con.Close();
            }

            return(Task.FromResult(listPhoto));
        }
コード例 #2
0
        public async Task <IActionResult> PhotoSave(IFormFile photo, CancellationToken cancellationToken)
        {
            if (photo != null && photo.Length > 0)
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/photos", photo.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await photo.CopyToAsync(stream, cancellationToken);

                    var returnPath = $"photos/{photo.FileName}";


                    var photoDto = new PhotoDto
                    {
                        Path = returnPath
                    };

                    var result = DataResult <PhotoDto> .Success(photoDto, Contract.Enums.StatusCode.Ok);

                    return(CreateResult(result));
                }
            }

            var failResult = MessageResult.Error("When Image Upload An Occurrent Error", Contract.Enums.StatusCode.Failed);

            return(CreateMesageResult(failResult));
        }
コード例 #3
0
        public async Task <ActionResult <PhotoDto> > PutPhoto([FromRoute] int id, [FromBody] PhotoDto photoDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != photoDto.ID)
            {
                return(BadRequest());
            }

            Photo photo = DtoToEntityIMapper.Map <PhotoDto, Photo>(photoDto);

            repository.ModifyEntryState(photo, EntityState.Modified);

            try
            {
                await uoW.SaveAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhotoExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #4
0
        public async Task <IActionResult> PutPhoto(long id, PhotoDto photoDto)
        {
            if (id != photoDto.Id)
            {
                return(BadRequest());
            }

            var photo = _context.Photos.First(p => p.Id == photoDto.Id);

            photo.Comment = photoDto.Comment;
            _context.Entry(photo).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhotoExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #5
0
        public static async Task HandleUploadPhoto(Server server, CommunicationClient client)
        {
            var name      = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(Photo.PhotoNameLength));
            var extension = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(Photo.PhotoExtensionLength));
            var fileSize  = ConversionHandler.ConvertBytesToLong(await client.StreamCommunication.ReadAsync(ProtocolConstants.LongTypeLength));

            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(extension))
            {
                ProtocolHelpers.SendMessageCommand(ProtocolConstants.ResponseCommands.Ok, client, "Input Error");
            }

            var photo = new PhotoDto()
            {
                Name      = name,
                Extension = extension,
                FileSize  = fileSize,
                UserEmail = client.User.Email
            };

            await server.Service.UploadPhotoAsync(photo);

            var fileName = $"{PhotosPath}\\Image_{photo.Id}{extension}";

            await FileHandler.ReceiveFileWithStreams(fileSize, fileName, client.StreamCommunication);

            loggerService.SendMessages("Image uploaded");

            ProtocolHelpers.SendMessageCommand(ProtocolConstants.ResponseCommands.Ok, client, "Added succesfully");
        }
コード例 #6
0
        public async Task <HttpResponseMessage> Add()
        {
            try
            {
                var provider = new CustomMultipartFormDataStreamProvider(workingFolder);

                await Task.Run(async() => await Request.Content.ReadAsMultipartAsync(provider));

                var photoDto = new PhotoDto();

                foreach (var file in provider.FileData)
                {
                    var data     = provider.FormData;
                    var fileInfo = new FileInfo(file.LocalFileName);

                    photoDto = new PhotoDto
                    {
                        Name           = fileInfo.Name,
                        PhotographerId = int.Parse(data.Get("Content[PhotographerId]"))
                    };

                    photoService.Add(photoDto);
                }
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
コード例 #7
0
        public static async Task HandleViewCommentsPhoto(FileServer.Server server, CommunicationClient client)
        {
            var photoIdParsed = ConversionHandler.ConvertBytesToLong(await client.StreamCommunication.ReadAsync(ProtocolConstants.LongTypeLength));

            ProtocolHelpers.SendResponseCommand(ProtocolConstants.ResponseCommands.ListComments,
                                                client.StreamCommunication);

            var photo = new PhotoDto()
            {
                Id = photoIdParsed
            };
            var comments = await server.Service.GetCommentsAsync(photo);

            var length = comments.Count() * (User.UserEmailLength + User.UserNameLength + Comment.CommentLength);

            var data = ConversionHandler.ConvertIntToBytes(length);

            client.StreamCommunication.Write(data);

            comments.ToList().ForEach((elem) =>
            {
                var comment = new Comment()
                {
                    Message     = elem.Message,
                    Commentator = new User()
                    {
                        Email = elem.UserEmail,
                        Name  = elem.UserName
                    }
                };
                ProtocolHelpers.SendCommentData(client.StreamCommunication, comment);
            });

            loggerService.SendMessages("Comments listed correctly");
        }
コード例 #8
0
        public async Task <PhotoDto> GetRemotePhoto(Priority priority, int id)
        {
            PhotoDto conference = null;

            Task <PhotoDto> getPhotoTask;

            switch (priority)
            {
            case Priority.Background:
                getPhotoTask = _apiService.Background.GetPhoto(id);
                break;

            case Priority.UserInitiated:
                getPhotoTask = _apiService.UserInitiated.GetPhoto(id);
                break;

            case Priority.Speculative:
                getPhotoTask = _apiService.Speculative.GetPhoto(id);
                break;

            default:
                getPhotoTask = _apiService.UserInitiated.GetPhoto(id);
                break;
            }

            if (Connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                conference = await GetPolicy().ExecuteAsync(() => getPhotoTask).ConfigureAwait(false);
            }

            return(conference);
        }
コード例 #9
0
        public async Task <IHttpActionResult> PutPhoto(int id, PhotoDto photoDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != photoDto.ID)
            {
                return(BadRequest());
            }
            var photo = DtoToEntityIMapper.Map <PhotoDto, Photo>(photoDto); ////

            UoW.GetRepository <Photo>().ModifyEntityState(photo);

            try
            {
                await UoW.SaveAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhotoExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #10
0
        public async Task <PhotoDto> AddPhotoAsync(string userId, PhotoDto photoDto)
        {
            var currentUser = await _context.Users
                              .Where(u => u.Id == userId)
                              .Include(i => i.Photo)
                              .FirstOrDefaultAsync();

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

            if (currentUser == null)
            {
                return(null);
            }

            if (currentUser.Photo != null)
            {
                _context.Photos.Remove(currentUser.Photo);
            }

            currentUser.Photo = photo;

            await _context.SaveChangesAsync();

            return(_mapper.Map <PhotoDto>(photo));
        }
コード例 #11
0
        public void Add(PhotoDto photoDto)
        {
            var photo = Mapper.Map <Photo>(photoDto);

            photoRepository.Create(photo);
            photoRepository.Save();
        }
コード例 #12
0
 public PhotoDto ActionPhoto(PhotoDto photoDto)
 {
     try
     {
         var         photoEntity = GetSingleOrDefaultBaseEntity(photoDto.Id, isValid: true);
         EntityState entityState = EntityState.Modified;
         if (photoEntity is null)
         {
             photoEntity = new Photo()
             {
                 Name     = photoDto.Name,
                 Url      = photoDto.Url,
                 RecipeId = photoDto.RecipeId,
             };
             entityState = EntityState.Added;
         } // Add case
         else
         {
             photoEntity.Name     = photoDto.Name;
             photoEntity.Url      = photoDto.Url;
             photoEntity.RecipeId = photoDto.RecipeId;
         } // Update case
         Context.Entry(photoEntity).State = entityState;
         Context.SaveChanges();
         photoDto.Id = photoEntity.Id;
         return(photoDto);
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #13
0
        public async Task <PhotoDto> InsertPhoto(PhotoDto objPhotoDto)
        {
            PhotoDto objUserPhoto = new PhotoDto();

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("usp_InsertPhoto", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@FkUserId", objPhotoDto.FkUserId);
                cmd.Parameters.AddWithValue("@url", objPhotoDto.url);
                cmd.Parameters.AddWithValue("@Description", objPhotoDto.Description == null ? "" : objPhotoDto.Description);
                cmd.Parameters.AddWithValue("@AddDate", objPhotoDto.AddDate);
                cmd.Parameters.AddWithValue("@IsMain", objPhotoDto.IsMain);
                cmd.Parameters.AddWithValue("@PublicId", objPhotoDto.PublicId);

                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    objUserPhoto.Id          = Convert.ToInt32(rdr["Id"]);
                    objUserPhoto.url         = Convert.ToString(rdr["Url"]);
                    objUserPhoto.Description = Convert.ToString(rdr["Description"]);
                    objUserPhoto.AddDate     = Convert.ToDateTime(rdr["AddDate"]);
                    objUserPhoto.IsMain      = Convert.ToBoolean(rdr["IsMain"]);
                    objUserPhoto.PublicId    = Convert.ToString(rdr["PublicId"]);
                }
                con.Close();
            }

            return(await Task.FromResult(objUserPhoto));
        }
コード例 #14
0
        public IHttpActionResult SetMainUserPhoto(PhotoDto photo)
        {
            try
            {
                var userId = User.Identity.GetUserId();

                var UserPhotos = _ctx.UserPhotos.Where(x => x.UserId == userId).ToList();

                for (int i = 0; i < UserPhotos.Count; i++)
                {
                    if (UserPhotos[i].IsMain == true)
                    {
                        UserPhotos[i].IsMain = false;
                    }
                }


                UserPhotos.Single(x => x.Id == photo.photoId).IsMain = true;
                var photoToReturn = UserPhotos.Single(x => x.Id == photo.photoId);
                _ctx.SaveChanges();



                return(Ok(photoToReturn));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #15
0
        public IHttpActionResult SetMainHousePhoto(PhotoDto photo)
        {
            try
            {
                var userId      = User.Identity.GetUserId();
                var houseEntity = _ctx.HousePhotos
                                  .Include(x => x.House)
                                  .Single(x => x.Id == photo.photoId);

                var housePhotos = _ctx.HousePhotos.Where(x => x.House.UserId == userId && x.House.Id == houseEntity.House.Id).ToList();

                for (int i = 0; i < housePhotos.Count; i++)
                {
                    if (housePhotos[i].IsMain == true)
                    {
                        housePhotos[i].IsMain = false;
                    }
                }


                housePhotos.Single(x => x.Id == photo.photoId).IsMain = true;
                _ctx.SaveChanges();

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #16
0
        public async Task <NoteDto> Create()
        {
            var note  = JsonConvert.DeserializeObject <NoteDto>(Request.Form["note"]);
            var files = Request.Form.Files;

            var photoDtos = new List <PhotoDto>();

            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file.Length <= 0)
                    {
                        continue;
                    }
                    byte[] buffer;
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        buffer = ms.ToArray();
                    }

                    var photoDto = new PhotoDto
                    {
                        Name    = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'),
                        Content = Convert.ToBase64String(buffer)
                    };
                    photoDtos.Add(photoDto);
                }
            }
            note.Photos = photoDtos;
            return(await _notesService.CreateAsync(note));
        }
コード例 #17
0
        public List <PhotoDto> PreparePhotoDtoList(string userId, List <Photo> photos)
        {
            List <PhotoDto> photoDtos = new List <PhotoDto>();

            foreach (Photo photo in photos)
            {
                PhotoDto photoDto = Mapper.Map <PhotoDto>(photo);

                UserProfile userProfile = _unitOfWork.UserProfiles.SingleOrDefault(u => u.UserIdentityId == userId);

                Vote vote = null;
                photoDto.CanVote = false;
                if (userProfile != null)
                {
                    vote = userProfile.Votes.SingleOrDefault(v => v.Photo.PhotoId == photo.PhotoId);
                    if (vote == null)
                    {
                        photoDto.CanVote = true;
                    }
                }

                if (!photoDto.CanVote)
                {
                    if (vote != null)
                    {
                        photoDto.Liked = vote.Liked;
                    }
                }

                photoDtos.Add(photoDto);
            }
            return(photoDtos);
        }
コード例 #18
0
 public PhotoViewModel(PhotoDto photo)
 {
     this.Id           = photo.id;
     this.Title        = photo.title;
     this.AlbumId      = photo.albumId;
     this.Url          = photo.url;
     this.ThumbnailUrl = photo.thumbnailUrl;
 }
コード例 #19
0
 public static Photo <T> ConvertToModel <T>(this PhotoDto dto)
     where T : IPhotographable
 {
     return(new Photo <T>
     {
         FileName = dto.FileName,
         Path = dto.Path
     });
 }
コード例 #20
0
        public async Task <IActionResult> AddPhotoForUser(int UserId, [FromForm] PhotoCreationDto ObjPhotoCreationDto)
        {
            List <UsersDto> listUserDto  = new List <UsersDto>();
            UsersDto        objUserDto   = new UsersDto();
            PhotoDto        objPhotoDto  = new PhotoDto();
            var             file         = ObjPhotoCreationDto.File;
            var             uploadResult = new ImageUploadResult();


            if (UserId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            listUserDto = await objDattingDAL.GetUserList();

            objUserDto = listUserDto.FirstOrDefault(U => U.id == UserId);

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

                    uploadResult = _cloudinary.Upload(uploadsParams);
                }
            }

            ObjPhotoCreationDto.Url      = uploadResult.Uri.ToString();
            ObjPhotoCreationDto.PublicId = uploadResult.PublicId;

            objPhotoDto.PublicId    = ObjPhotoCreationDto.PublicId;
            objPhotoDto.IsMain      = false;
            objPhotoDto.Description = ObjPhotoCreationDto.Description;
            objPhotoDto.AddDate     = ObjPhotoCreationDto.DateAdded;
            objPhotoDto.url         = ObjPhotoCreationDto.Url;
            objPhotoDto.FkUserId    = UserId;

            if (!objUserDto.Photos.Any(x => x.IsMain))
            {
                objPhotoDto.IsMain = true;
            }
            PhotoDto objPhoto = new PhotoDto();

            objPhoto = await objPhotoDAL.InsertPhoto(objPhotoDto);

            if (objPhoto != null && objPhoto.Id > 0)
            {
                return(Ok(objPhoto));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #21
0
        private string GeneratePhotoUrl(PhotoDto photo)
        {
            var relativeUrl = Url.Action(nameof(GetPhotoContent), new {
                id = photo.Id
            });
            var url = "https://localhost:6001" + relativeUrl;

            return(url);
        }
コード例 #22
0
        public void PreparePhotoUrl(PhotoDto photo)
        {
            SharedAccessBlobPolicy policy = CreateSharedAccessPolicy();

            if (photo != null)
            {
                photo.Url = PrepareCloudUrl(photo.CloudFileName, policy);
            }
        }
コード例 #23
0
        public async Task <ActionResult <PhotoDto> > PostPhoto(PhotoDto photoDto)
        {
            _context.Photos.Add(new Photo
            {
                Comment = photoDto.Comment
            });
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetPhoto", new { id = photoDto.Id }, photoDto));
        }
コード例 #24
0
        public ActionResult AddPhoto(int id)
        {
            PhotoDto newPhoto = new PhotoDto();
            var      mapper   = new MapperConfiguration(cfg => cfg.CreateMap <PhotoDto, PhotoViewModel>()).CreateMapper();
            var      photo    = mapper.Map <PhotoDto, PhotoViewModel>(newPhoto);

            ViewBag.AlbumID = id;

            return(View(photo));
        }
コード例 #25
0
        public async Task <PhotoDto> GetPhoto(int id)
        {
            List <PhotoDto> listPhoto = new List <PhotoDto>();
            PhotoDto        objPhoto  = new PhotoDto();

            listPhoto = await objPhotoDAL.GetPhoto();

            objPhoto = listPhoto.FirstOrDefault(x => x.Id == id);
            return(objPhoto);
        }
コード例 #26
0
        public void WhenIMapAlbum_WithValidObject_IGetDto()
        {
            Photo    photo = GetPhoto();
            PhotoDto dto   = _mapper.ToPhotoDto(photo);

            Assert.AreEqual(photo.Title, dto.Title);
            Assert.AreEqual(photo.Id, dto.Id);
            Assert.AreEqual(photo.ThumbnailUrl, dto.ThumbnailUrl);
            Assert.AreEqual(photo.Url, dto.Url);
        }
コード例 #27
0
        public async Task <IActionResult> Put(int?id, [FromBody] PhotoDto photo)
        {
            try
            {
                if (id.Value == 0)
                {
                    throw new Exception("The resource id must not be 0!");
                }

                if (Request.Form.Files.Count == 0)
                {
                    throw new Exception("No files submited.");
                }

                var file = Request.Form.Files[0];

                StringValues idProperty;
                if (!Request.Form.TryGetValue("IdProperty", out idProperty))
                {
                    throw new Exception("Missing parameter (IdProperty)!");
                }

                using (var stream = file.OpenReadStream())
                {
                    using (var mStream = new MemoryStream())
                    {
                        stream.CopyTo(mStream);

                        await this._Dao.Update(
                            new PhotoDto
                        {
                            Id         = id.Value,
                            Content    = mStream.ToArray(),
                            FileName   = file.FileName,
                            IdProperty = idProperty.ToString().ExtConvertToInt32()
                        }
                            );
                    }
                }

                return(Accepted());
            }
            catch (Exception ex)
            {
                switch (ex.InnerException)
                {
                case Exception exception:
                    return(BadRequest(exception.Message));

                // Not InnerException
                default:
                    return(BadRequest(ex.Message));
                }
            }
        }
コード例 #28
0
 private Photo Map(PhotoDto dto)
 {
     return(new Photo()
     {
         Id = dto.Id,
         AlbumId = dto.AlbumId,
         Title = dto.Title,
         ThumbnailUrl = dto.ThumbnailUrl,
         Url = dto.Url
     });
 }
コード例 #29
0
        private PhotoDto ConvertToPhotoDto(Photo photoModel)
        {
            var dto = new PhotoDto
            {
                Id      = photoModel.Id,
                Content = Convert.ToBase64String(photoModel.Content),
                Name    = photoModel.FileName
            };

            return(dto);
        }
コード例 #30
0
        public static Photo BuildPhoto(PhotoDto obj)
        {
            var photo = obj.Map <PhotoDto, Photo>();

            photo.Context = photo.Context.Substring(base64Header.Length);

            var byteContext = Convert.FromBase64String(photo.Context);

            photo.Context = Encoding.Default.GetString(byteContext, 0, byteContext.Length);

            return(photo);
        }
コード例 #31
0
        public ActionResult UploadPhoto(UploadPhotoModel pm)
        {        
            if (ModelState.IsValid)
            {
                var currentTime = DateTime.Now;            
                string filePath = "/Files/"+ currentTime.ToString("dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".")+Path.GetFileName(pm.File.FileName);
                pm.File.SaveAs(Server.MapPath(filePath));
                var photoDto = new PhotoDto
                {
                    UserId = (User as PhotoGalleryPrincipal).Id,
                    CreateTime = currentTime,
                    PhotoOwner = User.Identity.Name,
                    Title = pm.Title,
                    AverageRating = 0,
                    CurrentUserRating = 0,
                    ImagePath = filePath
                };

                _service.AddPhoto(photoDto);
                return RedirectToAction("Manage", new { login=User.Identity.Name});
            }
            return PartialView("CreatePhoto",pm);             
        }
コード例 #32
0
 private bool CanSeePhoto(PhotoDto dto, Guid userid)
 {
     if (userid == dto.UploadedBy.Id)
         return true;
     else
         return dto.Privacy.CanSee(userid);
 }