예제 #1
0
        public Photo AddPhoto(string name, string description, bool isPublic, string source, string thumbnail, IEnumerable <Tag> tags, int albumId)
        {
            var album = UnitOfWork.Albums.GetById(albumId);

            if (album == null)
            {
                throw new DataException(string.Format("Album with id {0} does not exist.", albumId));
            }

            var tagEntities = new List <TagEntity>();

            var entity = new PhotoEntity()
            {
                Albums          = new List <AlbumEntity>(new[] { album }),
                CreatedOn       = DateTime.UtcNow,
                Description     = description,
                IsPublic        = isPublic,
                Name            = name,
                Source          = source,
                ThumbnailSource = thumbnail,
                Tags            = tagEntities
            };

            return(UnitOfWork.Photos.Add(entity).ToModel());
        }
예제 #2
0
        public void Upload_And_Download_Photo()
        {
            var          blobRepository = new BlobRepository();
            const string fileName       = @"Koala.jpg";
            var          filePath       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Images\\{fileName}");

            if (!File.Exists(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }
            var partitionKey = Guid.NewGuid();
            var entity       = new PhotoEntity(partitionKey.ToString(), Rowkey)
            {
                ID    = partitionKey,
                Title = "Koala",
                Owner = Owner,
            };

            string photoUrl;

            using (Stream file = File.OpenRead(filePath))
            {
                photoUrl = blobRepository.UploadBlob(file, entity);
            }

            Assert.IsNotNull(photoUrl);
            Assert.AreEqual($"https://medya.blob.core.windows.net:443/images/photo-{entity.ID}.jpg", photoUrl);
        }
예제 #3
0
        public async Task <IHttpActionResult> Post([FromBody] Photo photo)
        {
            var image = Convert.FromBase64String(photo.EncodedFile);

            var fileExtension = Path.GetExtension(photo.FileName);

            var key = String.Format("Photo-{0}{1}", Guid.NewGuid(), fileExtension);

            using (var stream = new MemoryStream(image))
            {
                CloudBlockBlob blockBlob = _container.GetBlockBlobReference(key);
                blockBlob.Properties.ContentType = photo.ContentType;
                await blockBlob.UploadFromStreamAsync(stream);
            }

            var photoEntity = new PhotoEntity
            {
                ContentLength = photo.ContentLength,
                ContentType   = photo.ContentType,
                Key           = key,
                Name          = photo.Name
            };

            if (photo.Name == null)
            {
                photoEntity.Name = photo.FileName;
                photoEntity.Name = photoEntity.Name.Replace(fileExtension, "");
            }

            _db.Photos.Add(photoEntity);
            await _db.SaveChangesAsync();

            return(Ok());
        }
예제 #4
0
        private void LoadPhotoImage(IPhotoImage photoImage)
        {
            PhotoEntity photo = CreatePhotoFromPhotoImage(photoImage);

            _loadedBytes += photo.Image.Length;
            _loadedPhotos.Add(photo);
        }
예제 #5
0
        public void UploadPhotos(IEnumerable <Photo> photos)
        {
            using (var context = dbContextFactory())
            {
                foreach (Photo photo in photos)
                {
                    var specDir = context.Directories.Find(photo.Parent);
                    if (specDir == null)
                    {
                        throw new ArgumentException("Directory does not exist!");
                    }

                    var photoEntity = new PhotoEntity
                    {
                        Name        = photo.Name,
                        Id          = photo.Id == Guid.Empty ? Guid.NewGuid() : photo.Id,
                        Parent      = specDir.Id,
                        Url         = photo.Url,
                        Description = photo.Description,
                        Metadata    = photo.Metadata,
                        CreatedDate = photo.CreatedDate,
                    };
                    context.Photos.Add(photoEntity);
                }
                context.SaveChanges();
            }
        }
예제 #6
0
        public static PhotoDetailModel PhotoEntityToPhotoDetailModel(PhotoEntity photoEntity)
        {
            var model = new PhotoDetailModel
            {
                Id          = photoEntity.Id,
                Name        = photoEntity.Name,
                Path        = photoEntity.Path,
                CreatedTime = photoEntity.CreatedTime,
                Format      = photoEntity.Format,
                AlbumId     = photoEntity.AlbumId,
                Resolution  = new ResolutionModel()
                {
                    Height = photoEntity.Resolution.Height,
                    Width  = photoEntity.Resolution.Width,
                    Id     = photoEntity.Resolution.Id
                },
                Note     = photoEntity.Note,
                Location = photoEntity.Location,
            };

            if (photoEntity?.Tags == null)
            {
                return(model);
            }
            var tags = TagEntitiesToTagModels(photoEntity.Tags);

            model.Tags = tags;

            return(model);
        }
        /// <summary>
        /// Saves an entity to Azure table storage
        /// </summary>
        /// <param name="tableName">The name of the table to save to</param>
        /// <param name="model">The PhotoModel object to be saved</param>
        /// <returns>System.String - the HTTP status code of the save operation</returns>
        public async Task <string> SaveToTableStorageAsync(
            string tableName,
            PhotoModel model)
        {
            //We use the DateAdded field for cross-partition queries
            DateTime now = System.DateTime.Now;

            model.DateAdded = now;

            PhotoEntity entity = new PhotoEntity(model);

            //These properties are used in a full table scan to populate
            //all photos for all users.  Needed as some way to get the
            //items for a single day for all users.
            entity.DayAdded   = now.Day;
            entity.MonthAdded = now.Month;
            entity.YearAdded  = now.Year;

            var client    = _account.CreateCloudTableClient();
            var table     = client.GetTableReference(tableName);
            var operation = TableOperation.InsertOrReplace(entity);

            var result = await table.ExecuteAsync(operation);

            //TODO:  Do we need to check the HTTP status code here?
            return(result.HttpStatusCode.ToString());
        }
예제 #8
0
        public async Task <bool> DeletePhotoAsync(PhotoEntity photo)
        {
            var request = new HttpRequestMessage();

            request.Method     = HttpMethod.Delete;
            request.RequestUri = BuildUri($"/api/photos/{UrlEncode(photo.Id)}");
            request.Headers.Add(HeaderNames.Accept, MediaTypeNames.Application.Json);

            var response = await SendAsync(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.NoContent:
            case HttpStatusCode.NotFound:
                return(true);

            case HttpStatusCode.Conflict:
            case HttpStatusCode.Unauthorized:
            case HttpStatusCode.Forbidden:
                return(false);

            default:
                throw new UnexpectedStatusCodeException(response.StatusCode);
            }
        }
        public ActionResult Delete(int id)
        {
            PhotoEntity photo = photoService.GetPhotoEntity(id);

            TempData["message"] = string.Format("Photo has been deleted.", photo.Description);
            photoService.DeletePhoto(photo);
            return(RedirectToAction("GetPhotoForUser"));
        }
 private PhotoEntity FromViewModel(PhotoViewModel photoViewModel)
 {
     var photo = new PhotoEntity(this.User.Identity.Name);
     photo.RowKey = photoViewModel.RowKey ?? photo.RowKey;
     photo.Title = photoViewModel.Title;
     photo.Description = photoViewModel.Description;
     return photo;
 }
 /// <summary>
 /// Method UpdatePhoto update exists photo.
 /// </summary>
 /// <param name="photo">PhotoEntity that need update.</param>
 public void UpdatePhoto(PhotoEntity photo)
 {
     try {
         photoRepository.Update(photo.ToDalPhoto());
     }
     catch (Exception ex) {
         logger.Error(logger.GetMessage("Update photo was failed.", this), ex);
     }
 }
예제 #12
0
        public void LoadPhoto(PhotoEntity photo, string login)
        {
            DalUser  user     = uow.Users.GetByPredicate(dalUser => dalUser.Login == login);
            DalPhoto dalPhoto = photo.ToDalPhoto();

            dalPhoto.UserId = user.Id;
            uow.Photos.Create(dalPhoto);
            uow.Commit();
        }
예제 #13
0
        public void DeletePhoto(int photoId)
        {
            PhotoEntity photoEntity = _photosContext.Photos.Where(photo => photo.Id == photoId).Single();

            _photosContext.Entry(photoEntity).State = System.Data.Entity.EntityState.Deleted;
            _photosContext.SaveChanges();

            RemoveAlbumIfEmpty(photoEntity.AlbumId);
        }
        public IActionResult UpdatePhoto(uint id, [FromBody] PhotoEntity photo)
        {
            if (photo == null)
            {
                return(BadRequest());
            }

            return(_photoService.EditPhoto(id, photo.Username, photo.Description) ? Ok() : NotFound());
        }
예제 #15
0
        public async Task <string> UploadBlobAsync(Stream photo, PhotoEntity entity)
        {
            if (photo == null)
            {
                throw new ArgumentNullException(nameof(photo));
            }

            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            string fullPath = null;

            //Stopwatch timespan = Stopwatch.StartNew();

            try
            {
                var storageAccount = StorageUtils.StorageAccount;
                // Create the blob client and reference the container
                var blobClient = storageAccount.CreateCloudBlobClient();
                var container  = blobClient.GetContainerReference(Constants.Azure.Blobs.Images);
                if (await container.CreateIfNotExistsAsync())
                {
                    // Enable public access on the newly created "images" container
                    await container.SetPermissionsAsync(new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
                }


                // Create a unique name for the images we are about to upload
                string imageName = $"photo-{entity.ID}.jpg";

                // Upload image to Blob Storage
                var blockBlob = container.GetBlockBlobReference(imageName);
                blockBlob.Properties.ContentType = ContentType;
                await blockBlob.UploadFromStreamAsync(photo);

                // Convert to be HTTP based URI (default storage path is HTTPS)
                var uriBuilder = new UriBuilder(blockBlob.Uri)
                {
                    Scheme = "https"
                };
                fullPath = uriBuilder.ToString();

                //timespan.Stop();
                //log.TraceApi("Blob Service", "PhotoService.UploadPhoto", timespan.Elapsed, "imagepath={0}", fullPath);
            }
            catch (Exception ex)
            {
                //log.Error(ex, "Error upload photo blob to storage");
            }

            return(fullPath);
        }
예제 #16
0
 public static PhotoListModel PhotoEntityToPhotoListModel(PhotoEntity photoEntity)
 {
     return(new PhotoListModel
     {
         Id = photoEntity.Id,
         Name = photoEntity.Name,
         Path = photoEntity.Path,
         CreatedTime = photoEntity.CreatedTime
     });
 }
예제 #17
0
        public void Update(PhotoEntity photo)
        {
            if (ReferenceEquals(photo, null))
            {
                throw new ArgumentNullException(nameof(photo));
            }

            photoRepository.Update(photo.ToDalPhoto());
            uow.Commit();
        }
예제 #18
0
        //public int setTask(List<TaskEntity> tasc) {
        //    var db = new DBConnection();
        //    return db.InsertAll(tasc);
        //}

        //public int setTestimony(List<TestimonyEntity> Testimony) {
        //    var db = new DBConnection();
        //    return db.InsertAll(Testimony);
        //}

        //public int setTechCard(List<TechnicalCardEntity> TechCard) {
        //    var db = new DBConnection();
        //    return db.InsertAll(TechCard);
        //}

        public int setPhoto(TaskEntity Task, string Path)
        {
            var db    = new DBConnection();
            var photo = new PhotoEntity {
                IDTask = Task.IDTask,
                Path   = Path,
            };

            return(db.Insert(photo));
        }
 /// <summary>
 /// Method DeletePhoto delete photo.
 /// </summary>
 /// <param name="photo">Entity that need delete.</param>
 public void DeletePhoto(PhotoEntity photo)
 {
     try {
         photoRepository.Delete(photo.ToDalPhoto());
         uow.Commit();
     }
     catch (Exception ex) {
         logger.Error(logger.GetMessage("Delete photo was failed.", this), ex);
     }
 }
 private PhotoViewModel ToViewModel(PhotoEntity photo)
 {
     return new PhotoViewModel
     {
         PartitionKey = photo.PartitionKey,
         RowKey = photo.RowKey,
         Title = photo.Title,
         Description = photo.Description
     };
 }
        public IActionResult PostPhoto([FromBody] PhotoEntity photo)
        {
            if (photo == null)
            {
                return(BadRequest());
            }

            _photoService.CreatePhoto(photo);
            return(CreatedAtAction(nameof(GetPhoto), new { photo = photo }, photo));
        }
예제 #22
0
 public static DalPhoto ToDal(this PhotoEntity photoEntity)
 {
     return(new DalPhoto()
     {
         Id = photoEntity.Id,
         AlbumId = photoEntity.AlbumId,
         LoadDateTime = photoEntity.LoadDateTime,
         Name = photoEntity.Name,
         Path = photoEntity.Path
     });
 }
        /// <summary>
        /// Creates a new photo
        /// </summary>
        /// <param name="photo">the photo entity that holds the data</param>
        /// <returns>
        /// true - if the photo was created<para/>
        /// false - if the photo wasn't created<para/>
        /// The comment can't be created if the user that requested the action doesn't exist
        /// </returns>
        public bool CreatePhoto(PhotoEntity photo)
        {
            if (!Exists(photo.Id))
            {
                photo.Date = DateTime.Now.ToString("HH:mm:ss dd/MM/yyyy");
                _photos.Add(photo.Id, photo);
                return(true);
            }

            return(false);
        }
        public ActionResult DeletePhoto(int id)
        {
            PhotoEntity photo = photoService.GetPhotoEntity(id);

            if (photo == null)
            {
                return(HttpNotFound());
            }

            return(View(photo.ToMvcPhoto()));
        }
 public static DalPhoto ToDalPhoto(this PhotoEntity p)
 {
     return(new DalPhoto()
     {
         Id = p.Id,
         Image = p.Image,
         Description = p.Description,
         LoadDate = p.LoadDate,
         UserId = p.UserId,
         LikesCount = p.likesNumber
     });
 }
 /// <summary>
 /// Method ToDalPhoto convert PhotoEntity to DalPhoto.
 /// </summary>
 /// <param name="photoEntity">PhotoEntity that need convert.</param>
 /// <returns>DalPhoto entity.</returns>
 public static DalPhoto ToDalPhoto(this PhotoEntity photoEntity)
 {
     return(new DalPhoto()
     {
         Id = photoEntity.Id,
         Description = photoEntity.Description,
         Image = photoEntity.Image,
         CreatedOn = photoEntity.CreatedOn,
         CategoryId = photoEntity.CategoryId,
         UserId = photoEntity.UserId
     });
 }
예제 #27
0
 public static PhotoRecord ToRecord(this PhotoEntity entity)
 {
     return(new PhotoRecord
     {
         CloudUrl = entity.CloudUrl,
         CreatedAt = entity.CreatedAt,
         EntityId = entity.EntityId,
         Order = entity.Order,
         Height = entity.Height,
         Width = entity.Width
     });
 }
예제 #28
0
 public static PhotoViewModel ToMvcPhoto(this PhotoEntity photoEntity)
 {
     return(new PhotoViewModel()
     {
         PhotoId = photoEntity.Id,
         AlbumId = photoEntity.AlbumId,
         Name = photoEntity.Name,
         LoadDateTime = photoEntity.LoadDateTime,
         Path = photoEntity.Path,
         LikesAmount = photoEntity.LikesAmount,
     });
 }
예제 #29
0
 public static PhotoViewModel ToMvcPhoto(this PhotoEntity photoEntity)
 {
     return(new PhotoViewModel()
     {
         Id = photoEntity.Id,
         Description = photoEntity.Description,
         Image = photoEntity.Image,
         CreatedOn = photoEntity.CreatedOn,
         CategoryId = photoEntity.CategoryId,
         UserId = photoEntity.UserId,
     });
 }
예제 #30
0
        public void DeletePhoto(PhotoEntity photo)
        {
            using (MvcApplicationDB _context = new MvcApplicationDB())
            {
                PhotoEntity photoToBeRemoved = _context.Photos
                                               .FirstOrDefault(p => p.PhotoEntityId == photo.PhotoEntityId);

                _context.Photos.Remove(photoToBeRemoved);

                _context.SaveChanges();
            }
        }