Exemplo n.º 1
0
        //consider changing the out parameter to a validation type object
        //public void Save(IPhoto photo, out bool success)
        //{
        //    Checks.Argument.IsNotNull(photo, "photo");

        //    success = false;

        //    if (null == _repo.FindByPhotoId(photo.PhotoId))
        //    {
        //        try
        //        {
        //            _repo.Add(photo);
        //            success = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            success = false;
        //        }
        //    }
        //}

        public void Save(IPhoto photo, IImageFormatSpec mediaFormat, out bool success)
        {
            success = false;
            Checks.Argument.IsNotNull(photo, "photo");
            Checks.Argument.IsNotNull(mediaFormat, "mediaFormat");


            //ValidateTempImageStorage(tempImageStorage, out validationState);

            //if (!validationState.IsValid)
            //{
            //    return;
            //}

            if (null == this.GetPhoto(photo.PhotoId))
            {
                try
                {
                    _repo.Add(photo);
                    success = true;
                }
                catch (Exception ex)
                {
                    success = false;
                    //var valState = new ValidationState();
                    //valState.Errors.Add(new ValidationError("Id.AlreadyExists", tempImageStorage, ex.Message));
                    //validationState.Append(typeof(ITempImageStorage), valState);
                }
            }
        }
Exemplo n.º 2
0
        public void AddToUser(string address, int id)
        {
            Photo photo = new Photo {
                Address = $"{_file}{address}", UserId = id
            };

            try
            {
                _photoRepository.Add(photo);
            }
            catch (DbEntityValidationException ex)
            {
                throw new IncorrectDataException(DbEntityValidationExceptioErrorMessages.ErrorMessages(ex));
            }
        }
Exemplo n.º 3
0
        public Photo Add(Photo photo)
        {
            _repository.Add(photo);
            this.SaveChanges();

            return(photo);
        }
Exemplo n.º 4
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            var photo = new Model.Models.Photos
            {
                Id           = Guid.NewGuid(),
                Name         = tbName.Text,
                Path         = lblPath.Text,
                CreationDate = DateTime.Now
            };


            var personId = ((Model.Models.Person)cbPersons.SelectedItem).Id;

            photo.People.Add(_personRepository.GetById(personId));

            var typeId = ((Model.Models.Type)cbTypes.SelectedItem).Id;

            photo.Types.Add(_typeRepository.GetById(typeId));

            var eventId = ((Model.Models.Event)cbEvent.SelectedItem).Id;

            photo.Event = _eventRepository.GetById(eventId);

            var placeId = ((Model.Models.Places)cbPlaces.SelectedItem).Id;

            photo.Places.Add(_placeRepository.GetById(placeId));

            _repository.Add(photo);
            Close();
        }
Exemplo n.º 5
0
        public ActionResult UploadPhoto(Photo photo, HttpPostedFileBase imageFile)
        {
            if (!ModelState.IsValid)
            {
                return(View(photo));
            }
            if (imageFile == null)
            {
                return(View(photo));
            }

            photo.Url          = "~/GalleryPhotos/" + imageFile.FileName;
            photo.UploadedDate = DateTime.Now;
            photo.PhotoID      = Guid.NewGuid();
            if (User.Identity.IsAuthenticated)
            {
                photo.uploader = new Guid(User.Identity.GetUserId());
            }
            var photoData = photo.Transform();

            PhotoRepository.Add(photoData);

            imageFile.SaveAs(Path.Combine(Server.MapPath("~/GalleryPhotos"), imageFile.FileName));

            return(PartialView());
        }
Exemplo n.º 6
0
 public ActionResult Create(CreatePhotosViewModel model)
 {
     try
     {
         string FileName = UploadFile(model.File) ?? string.Empty;
         if (ModelState.IsValid)
         {
             if (model.ProjectId == -1)
             {
                 ModelState.AddModelError("", "please review the input fileds");
                 return(View(GetAllProjects()));
             }
             var projects = projectRepository.Find(model.ProjectId);
             var photo    = new Photo
             {
                 Image   = FileName,
                 Project = projects
             };
             PhotoRepository.Add(photo);
             return(RedirectToAction("index"));
         }
         return(View(model));
     }
     catch
     {
         return(View(model));
     }
 }
Exemplo n.º 7
0
        public async Task <IActionResult> Post(string nombre_especie, string familia, List <string> descripciones,
                                               List <IFormFile> archivos)
        {
            string filePath;
            Task   result;

            Specie spe = new Specie();

            spe.Name    = nombre_especie;
            spe.Family  = familia;
            spe.Gallery = new List <Photo>();
            result      = _SpecieRepository.Add(spe);

            Core.MakeSpecieFolder(spe.Id.ToString());

            for (int i = 1; i < (archivos.Count + 1); i++)
            {
                Photo photo = new Photo();
                photo.Description = descripciones[i - 1];
                _PhotoRepository.Add(photo);
                _SpecieRepository.AddPhoto(spe.Id, photo);
                string[] extension = (archivos[i - 1].FileName).Split('.');
                filePath = Path.Combine(Core.SpecieFolderPath(spe.Id.ToString()), photo.Id.ToString() + "." + extension[1]);
                if (archivos[i - 1].Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await archivos[i - 1].CopyToAsync(stream);
                    }
                }
            }

            if (result.Status == TaskStatus.RanToCompletion || result.Status == TaskStatus.Running ||
                result.Status == TaskStatus.Created || result.Status == TaskStatus.WaitingToRun)
            {
                TempData["creacion"] = 1;
            }
            else
            {
                TempData["creacion"] = -1;
            }

            return(Redirect("/api/bpv/specie/index/"));
        }
 public IActionResult Create(Photo myphoto)
 {
     if (ModelState.IsValid)
     {
         var p = photoRepository.Add(myphoto);
         return(RedirectToAction("index", p));
     }
     else
     {
         return(View());
     }
 }
        public async Task <IActionResult> Upload(string id, PhotoResource photoResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }


            var resulut = await repository.Add(id, photoResource);

            return(Ok());
        }
Exemplo n.º 10
0
        /// <summary>
        /// Insert the processed fields into the database table tblPhoto
        /// </summary>
        private void InsertHEPhotoTable(IUnitOfWork uow, int mwfPhotoId, int?orderId, int?instructionId, int?driverId)
        {
            Photo photo = new Photo();

            IPhotoRepository photoRepo = DIContainer.CreateRepository <IPhotoRepository>(uow);

            photo.MwfPhotoID    = mwfPhotoId;
            photo.OrderID       = orderId;
            photo.InstructionID = instructionId;
            photo.DriverID      = driverId;

            photoRepo.Add(photo);
        }
        public ActionResult AddPhoto(string photoUrl, string comment)
        {
            // test if parameters are correct
            string userId = User.Identity.GetUserId();
            var    p      = new Photo {
                photoUrl = photoUrl, Caption = comment, DateCreated = DateTime.Now, UserId = userId
            };

            photoRepository.Add(p);
            // var model = photoRepository.Add(new Photo(photoUrl,comment,userId));

            return(RedirectToAction("MyProfile", "Home"));
        }
Exemplo n.º 12
0
        public IActionResult Create([FromBody] PhotoViewModel photo)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Photo _newPhoto = Mapper.Map <PhotoViewModel, Photo>(photo);

            _photoRepository.Add(_newPhoto);
            _photoRepository.Commit();

            photo = Mapper.Map <Photo, PhotoViewModel>(_newPhoto);

            return(new OkObjectResult(photo));
        }
Exemplo n.º 13
0
        public async Task <HttpResponseMessage> AddPhoto(int id, FileData file)
        {
            try
            {
                await _photo.Add(id, new MemoryStream(file.Data), file.FileName, file.MimeType);

                _unit.Save();
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }

            return(Request.CreateResponse(HttpStatusCode.Accepted,
                                          string.Format("The photo was added to good - {0} id successfuly", id)));
        }
Exemplo n.º 14
0
 public Photo Add(Photo photo, IFormFile file)
 {
     if (file != null)
     {
         bool  fileAdded = _fileRepository.Add(file);
         Image image     = new Image
         {
             FileName    = file.FileName,
             ContentType = file.ContentType,
             Timestamp   = DateTime.UtcNow
         };
         image         = _imageRepository.Add(image);
         photo.ImageId = image.ImageId;
     }
     photo.Timestamp = DateTime.UtcNow;
     return(_photoRepository.Add(photo));
 }
Exemplo n.º 15
0
        public IActionResult UploadPhotoAndStartSession([FromBody] PhotoRequest photoRequest,
                                                        [FromServices] UserManager <ApplicationUser> userManager,
                                                        [FromServices] SessionTracker sessionTracker,
                                                        [FromServices] IImageDecryptor imageDecryptor,
                                                        [FromServices] RecognitionTaskQueue taskQueue,
                                                        [FromServices] IConfiguration configuration,
                                                        [FromServices] AnalyticsAgent agent)
        {
            using (_logger.BeginScope(nameof(UploadPhotoAndStartSession)))
            {
                //validate request
                if (photoRequest == null)
                {
                    _logger.LogError("Attempt to start a session because of null mobile photo request.");
                    return(BadRequest(new { message = "Error: something in your request is empty" }));
                }

                try
                {
                    //try start new session
                    var session = sessionTracker.StartSession(Convert.ToInt32(userManager.GetUserId(HttpContext.User)), photoRequest.TimeStamp);

                    //decrypt image and send to db
                    _logger.LogInformation($"Trying decrypt image...");
                    var decrypredImage = imageDecryptor.Decrypt(Convert.FromBase64String(photoRequest.Image));
                    var image          = new Photo(session.SessionID, decrypredImage, photoRequest.TimeStamp);
                    _photoRepository.Add(image);
                    _logger.LogInformation($"Ecrypted image was decrypted and saved to db.");

                    //send to analytics task queue
                    _logger.LogInformation($"Trying send photoId to RecognitionTaskQueue");
                    string modelName = configuration.GetSection("ModelName").Value; // get model name for analytics
                    taskQueue.Enqueue(new RecognitionTask(modelName, image.PhotoID));
                    _logger.LogInformation("Photo was sent to RecognitionTaskQueue");

                    var sessionResponse = new SessionResponse(session.SessionID);
                    return(Ok(sessionResponse));
                }
                catch (Exception ex)
                {
                    _logger.LogError("Exception caught: {0}, {1}", ex.Message, ex.StackTrace);
                    return(StatusCode(409, new { message = ex.Message }));
                }
            }
        }
Exemplo n.º 16
0
        public Photo uploadPhoto(string title, string uri, int albumID)
        {
            Album album = context.Albums.FirstOrDefault(s => s.Id == albumID);
            User  user  = context.Users.FirstOrDefault(s => s.Id == album.User_ID);

            var photo = new Photo()
            {
                Title        = title,
                Uri          = uri,
                AlbumId      = albumID,
                Username     = user.Username,
                DateUploaded = DateTime.Now
            };

            _photoRepository.Add(photo);
            _photoRepository.Commit();
            return(photo);
        }
Exemplo n.º 17
0
        public Photo uploadPhoto(string title, string uri, int albumID)
        {
            Album album = _albumRepository.GetSingle(albumID);
            Album a     = album;
            User  user  = _userRepository.GetSingle(album.User_ID);

            var photo = new Photo()
            {
                Title        = title,
                Uri          = uri,
                AlbumId      = albumID,
                Username     = user.Username,
                DateUploaded = DateTime.Now
            };

            _photoRepository.Add(photo);
            _photoRepository.Commit();
            return(photo);
        }
Exemplo n.º 18
0
        public IActionResult AddImage([FromForm] ImageFileVModel imageFileVModel)
        {
            var result = new TResultModel <FileNameVModel>(1);

            return(this.Wrapper(ref result, () =>
            {
                var file = imageFileVModel.file;
                var userId = _claimEntity.userId;
                var suffix = Path.GetExtension(file.FileName);//提取上传的文件文件后缀
                //if (this._pictureOptions.FileTypes.IndexOf(suffix) >= 0)//检查文件格式
                //{
                var fileName = $@"{Guid.NewGuid()}{suffix}";
                var baseUrl = _configuration["ImageUrl"];
                var imageUrl = Path.Combine(baseUrl, userId.ToString(), fileName);

                var path = Path.Combine($@"D:\Image", userId.ToString());
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var fullpath = Path.Combine(path, fileName);
                using (FileStream fs = System.IO.File.Create(fullpath)) //注意路径里面最好不要有中文
                {
                    file.CopyTo(fs);                                    //将上传的文件文件流,复制到fs中
                    fs.Flush();                                         //清空文件流
                }
                _photoRepository.Add(new HeyTom.Resources.Model.Photo()
                {
                    AlbumId = imageFileVModel.albumId,
                    CreateDate = DateTime.Now,
                    Name = file.FileName,
                    Path = imageUrl,
                    UserId = userId
                });

                result.TModel = new FileNameVModel()
                {
                    fileName = imageUrl
                };
            }, true));
        }
Exemplo n.º 19
0
        public IActionResult Post(Photo photo)
        {
            var currentUserProfile = GetCurrentUserProfile();

            if (currentUserProfile.Id != photo.UserProfileId)
            {
                return(Unauthorized());
            }
            if (photo == null)
            {
                return(BadRequest());
            }

            photo.ResolutionLevel = 300;
            if (photo.Attribute == null)
            {
                photo.Attribute = " ";
            }

            _photoRepository.Add(photo);
            return(CreatedAtAction(nameof(GetSingleById), new { id = photo.Id }, photo));
        }
Exemplo n.º 20
0
        public ActionResult Upload(int id)
        {
            var file    = Request.Files[0];
            var product = _products.Get(id);
            var count   = product.Photos.Count;

            var reader = new BinaryReader(file.InputStream);
            var data   = reader.ReadBytes(file.ContentLength);

            var photo = new Photo
            {
                IsDefault = (count == 0),
                Data      = data,
                SortOrder = count + 1,
                Product   = product
            };

            product.Photos.Add(photo);
            var newId = _photos.Add(photo);

            return(Json(new { success = true, id = newId }));
        }
Exemplo n.º 21
0
        public HttpResponseMessage Create(GoodsWebApi goodApi)
        {
            Good good = null;

            try
            {
                //good = _goods.Add(goodApi.GetGood());
                Parallel.ForEach(goodApi.Files, async f =>
                {
                    await _photo.Add(good.GoodId, new MemoryStream(f.Data), f.FileName, f.MimeType);
                });

                //_unit.Save();
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }

            return(Request.CreateResponse(HttpStatusCode.Accepted,
                                          string.Format("The good by id {0} was added successfuly", good.GoodId)));
        }
Exemplo n.º 22
0
 public ActionResult AddPhoto(Photo item, HttpPostedFileBase file)
 {
     if (ModelState.IsValid)
     {
         try
         {
             var fileName = Guid.NewGuid().ToString();
             var path     = Path.Combine(Server.MapPath("~/App_Data/ImagesBase/"), fileName);
             file.SaveAs(path);
             item.Created = DateTime.UtcNow;
             item.DataId  = fileName;
             _repository.Add(item, User.Identity.Name);
         }
         catch (Exception)
         {
             ViewBag.Message = "Upload failed";
             return(View("AddPhoto"));
         }
         ViewBag.Message = "Upload successful";
         return(View("AddPhoto", new Photo()));
     }
     return(View(item));
 }
Exemplo n.º 23
0
        public async Task <ActionResult> AddPhoto(IFormFile formFile)
        {
            var result = await _photoService.AddPhotoAsync(formFile);

            if (result.Error != null)
            {
                return(BadRequest(result.Error));
            }
            var photo = new Photo
            {
                Url      = result.SecureUrl.AbsoluteUri,
                PublicId = result.PublicId
            };

            _photoRepository.Add(photo);

            if (await _photoRepository.SaveAll())
            {
                return(Ok(photo.Id));
            }

            return(BadRequest("Nie udało się dodać zdjęcia"));
        }
Exemplo n.º 24
0
        public async Task <Result> Upload()
        {
            var filename = Request.Headers["x-filename"];

            if (string.IsNullOrEmpty(filename))
            {
                return(Result.Failure("Missing filename"));
            }

            if (Request.ContentLength == 0)
            {
                return(Result.Failure("Missing file contents"));
            }

            return(await Shield(async() =>
            {
                var originalContent = new byte[Request.ContentLength.GetValueOrDefault()];
                using (var memory = new MemoryStream(originalContent))
                {
                    await Request.Body.CopyToAsync(memory);
                }

                var visionAnalysisTask = _imageProcessor.ProcessPhoto(originalContent);
                var thumbnailContentTask = _imageProcessor.CreateThumbnail(originalContent);

                // run parallel independent APIs
                await Task.WhenAll(visionAnalysisTask, thumbnailContentTask);

                await _repository.Add(new Domain.Photo
                {
                    Name = filename,
                    OriginalContent = originalContent,
                    ThumbnailContent = thumbnailContentTask.Result,
                    VisionAnalysis = visionAnalysisTask.Result
                });
            }));
        }
        public ActionResult AddPhotoForCity([FromForm] PhotoForCreationDto photoForCreationDto)
        {
            /*
             * var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
             *
             * if (currentUserId == null)
             * {
             *  return Unauthorized();
             * }
             */
            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams
                    {
                        File = new FileDescription(file.Name, stream)
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            //photoForCreationDto.Url = uploadResult.Uri.ToString(); // Uri KULLANILMIYOR
            photoForCreationDto.Url      = uploadResult.Url.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

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

            _photoRepository.Add(photo);
            _photoRepository.SaveAll();
            return(Ok(photo));
        }
Exemplo n.º 26
0
 public void Add(Photo photo)
 {
     _PhotoRepository.Add(photo);
 }
Exemplo n.º 27
0
        public async Task <IActionResult> Post(ICollection <IFormFile> files)
        {
            var response = new FileResponse();

            if (ModelState.IsValid)
            {
                var uploads = Path.Combine(_env.ContentRootPath, "Uploads");

                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                        using (var fs = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                        {
                            using (var ms = new MemoryStream())
                            {
                                await file.CopyToAsync(ms);

                                var photo = new PhotoViewModel
                                {
                                    PropertyId   = null,
                                    BuildingId   = null,
                                    BuildingSeq  = null,
                                    ImageData    = ms.ToArray(),
                                    ImageName    = fileName,
                                    ImageSize    = ByteSize.FromBytes(file.Length).KiloBytes,
                                    DateTaken    = null,
                                    UploadedDate = DateTime.Now,
                                    UserId       = Convert.ToInt32(_userManager.GetUserId(User)),
                                    UploadedBy   = _userManager.GetUserName(User),
                                    MasterPhoto  = null,
                                    FrontPhoto   = null,
                                    PublicPhoto  = null,
                                    Status       = Status.Untagged.ToString(),
                                    Active       = true
                                };

                                _repo.Add(photo);
                            }
                        }
                    }
                }
            }

            //response = new FileResponse
            //{
            //    Files = new List<Photo>
            //    {
            //        new Photo {
            //            Name = fileName,
            //            Size = file.Length,
            //            Url = "",
            //            ThumbnailUrl = "",
            //            DeleteUrl = "",
            //            DeleteType = "DELETE"
            //        }
            //    }
            //};

            return(Ok(response));

            //var files = new FileResult
            //{
            //    FileNames = names,
            //    ContentTypes = contentTypes,
            //    Description = fileDescriptionShort.Description,
            //    CreatedTimestamp = DateTime.UtcNow,
            //    UpdatedTimestamp = DateTime.UtcNow,
            //};

            //_fileRepository.AddFileDescriptions(files);

            //return RedirectToAction("ViewAllFiles", "FileClient");
        }
Exemplo n.º 28
0
 public async Task AddAndSafe(Photo Photo)
 {
     _PhotoRepository.Add(Photo);
     await _PhotoRepository.Save();
 }
Exemplo n.º 29
0
 public void Add(Photo cat)
 {
     _photoRepository.Add(cat);
 }
Exemplo n.º 30
0
 public Photo AddPhoto(Photo photo)
 {
     return(_photoRepository.Add(photo));
 }