示例#1
0
        public async Task <IActionResult> Create(ExpenseCreateViewModel vm)
        {
            if (!TryValidateModel(vm))
            {
                return(View(vm));
            }

            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            var expense = new Expense
            {
                Description = vm.Description,
                Date        = vm.Date,
                Amount      = vm.Amount,
                CategoryId  = vm.SelectedCategory,
                ExpenseTags = vm.SelectedTags.Select(id => new ExpenseTag {
                    TagId = id
                }).ToList(),
                ExpenseAppUserId = userId
            };

            if (vm.File != null)
            {
                expense.PhotoPath = _photoService.AddPhoto(vm.File);
            }

            await _expenseDbContext.AddAsync(expense);

            await _expenseDbContext.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> Create(ProjectCreateViewModel vm)
        {
            if (!TryValidateModel(vm))
            {
                var statuses = await _portfolioDbContext.Statuses.ToListAsync();

                var tags = await _portfolioDbContext.Tags.ToListAsync();

                vm.Statuses = statuses.Select(item => new SelectListItem
                {
                    Value = item.Id.ToString(),
                    Text  = item.Description
                });
                vm.Tags = tags.Select(item => new SelectListItem
                {
                    Value = item.Id.ToString(),
                    Text  = item.Name
                });

                return(View(vm));
            }

            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            var project = new Project
            {
                Name        = vm.Name,
                Description = vm.Description,
                StartDate   = vm.StartDate,
                EndDate     = vm.EndDate,
                StatusId    = vm.SelectedStatus,
                ProjectTags = vm.SelectedTags.Select(id => new ProjectTag {
                    TagId = id
                }).ToList(),
                PortfolioUserId = userId
            };

            if (vm.File != null)
            {
                project.PhotoUrl = _photoService.AddPhoto(vm.File);
            }

            await _portfolioDbContext.AddAsync(project);

            await _portfolioDbContext.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
示例#3
0
        public async Task <ActionResult <PhotoDto> > AddPhoto(IFormFile file)
        {
            var user = await _userRepository.GetUserByUsername(User.GetUserName());

            var result = await _photoService.AddPhoto(file);

            if (result.Error != null)
            {
                return(BadRequest(result.Error.Message));
            }
            ;

            var photo = new Photo
            {
                Url      = result.SecureUrl.AbsoluteUri,
                PublicId = result.PublicId
            };

            if (user.Photos.Count == 0)
            {
                photo.IsMain = true;
            }

            await _photoRepository.AddPhoto(User.GetUserName(), photo);

            if (photo != null)
            {
                return(CreatedAtRoute("GetUserByName", new { username = user.UserName }, _mapper.Map <PhotoDto>(photo)));
            }

            return(BadRequest("Problem adding photo"));
        }
示例#4
0
        public IActionResult AddPhoto([FromForm] IFormFile photo)
        {
            var username = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            //add img to static folder
            var wwww_root   = _webHostEnvironment.WebRootPath;
            var path        = @"\profiles\" + username + @"\profile_photos\";
            var upload_path = wwww_root + path;

            var pathForFile = upload_path + photo.FileName;

            try
            {
                using (FileStream fileStream = System.IO.File.Create(pathForFile))
                {
                    photo.CopyTo(fileStream);
                    fileStream.Flush();
                }
            }
            catch (DirectoryNotFoundException e)
            {
                return(NotFound(pathForFile));
            }
            var pathOnServer = "http://" + Request.Host.Value + path + photo.FileName;
            var photoImage   = _photoService.AddPhoto(username, pathOnServer);

            return(Ok());
        }
        private void SetProfileImage(ProfileModel model, HttpPostedFileBase fileUpload)
        {
            var photo = new PhotoModel();

            if (!ReferenceEquals(fileUpload, null))
            {
                var previousAvatar = photoService.GetAllPhotos(model.Id).FirstOrDefault(p => p.IsAvatar);
                if (previousAvatar != null)
                {
                    previousAvatar.IsAvatar = false;
                    photoService.UpdatePhoto(previousAvatar);
                }
                photo.Data = new byte[fileUpload.ContentLength];
                fileUpload.InputStream.Read(photo.Data, 0, fileUpload.ContentLength);
                photo.MimeType = fileUpload.ContentType;
                photo.IsAvatar = true;
                photo.ProfileId.Add(model.Id);
                photoService.AddPhoto(photo.ToBllPhoto());
                var avatar = photoService.GetAllPhotos(model.Id).FirstOrDefault(p => p.IsAvatar == true);
                model.AvatarId = avatar.Id;
            }
            else
            {
                model.AvatarId = 0;
            }
        }
示例#6
0
        public ActionResult Create(CreatePhotoViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (model.File == null)
            {
                ViewBag.Error = "Please choose a file";
                return(View(model));
            }

            if (!_userProfileService.CanUserAddPhoto(User.Identity.GetUserId()))
            {
                ModelState.AddModelError("Error", "You have reached your maximum number of free photos");
                return(View(model));
            }

            Photo photo = Mapper.Map <Photo>(model);

            photo.UserId = User.Identity.GetUserId();

            _photoService.AddPhoto(photo, model.File.InputStream);

            return(RedirectToAction("Index"));
        }
        public async Task <Photo> Handle(AddPhotoCommand request, CancellationToken cancellationToken)
        {
            var photoUploadResult = _photoService.AddPhoto(request.File);

            var user = await _context.Users
                       .Include(u => u.Photos)
                       .SingleOrDefaultAsync(x => x.UserName == _currentUserService.Username);

            var photo = new Photo
            {
                Url = photoUploadResult.Url,
                Id  = photoUploadResult.PublicId
            };

            if (!user.Photos.Any(x => x.IsMain))
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            var success = await _context.SaveChangesAsync(cancellationToken) > 0;

            if (success)
            {
                return(photo);
            }
            throw new RestException(HttpStatusCode.BadRequest, new { Photo = _localizer["PhotoSaveError"] });
        }
示例#8
0
 public ActionResult Add2(FullPhotoViewModel qwe, HttpPostedFileBase main)
 {
     qwe.CategoryID  = qwe.SelectedID.ElementAt(0);
     qwe.CreatedTime = DateTime.Now;
     PhotoService.AddPhoto(AutoMapper.Mapper.Map <IPhoto>(qwe), main);
     return(RedirectToAction("ShowAllPhotos", new { id = qwe.CategoryID }));
 }
示例#9
0
        public async Task <OperationResult> ChangeAvatar(Guid uId, IFormFile avatar)
        {
            var user = Db.UserRepository.Get("Photo").FirstOrDefault(u => u.Id == uId);

            if (user == null)
            {
                return(new OperationResult(false, "User not found", "Id"));
            }

            if (user.Photo != null)
            {
                await _photoService.Delete(user.Photo.Id);
            }
            try
            {
                user.Photo = await _photoService.AddPhoto(avatar);

                Db.UserRepository.Update(user);
                await Db.SaveAsync();

                return(new OperationResult(true));
            }
            catch
            {
                return(new OperationResult(false, "Bad image file", "Id"));
            }
        }
示例#10
0
        public void AddPhoto(int productId, List <IFormFile> file)
        {
            string fullPath = Path.Combine(_env.WebRootPath, "Uploads/Products");

            foreach (var formFile in file)
            {
                string fileNameAdd, extension, fileName;
                if (formFile.Length > 0)
                {
                    fileNameAdd = Guid.NewGuid().ToString();
                    extension   = Path.GetExtension(formFile.FileName);
                    fileName    = fileNameAdd + extension;
                    using (var stream = new FileStream(Path.Combine(fullPath, fileName), FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }

                    var photo = new Photo()
                    {
                        PhotoUrl  = fileName,
                        ProductId = productId,
                        Sequance  = 0
                    };

                    _photoService.AddPhoto(photo);
                }
            }
        }
        public async Task <IActionResult> Upload(string id)
        {
            var tokenString = Request.Headers["Authorization"].ToString().Remove(0, 7);
            var handler     = new JwtSecurityTokenHandler();
            var jsonToken   = handler.ReadToken(tokenString);
            var token       = handler.ReadToken(tokenString) as JwtSecurityToken;
            var isPasswordChangeRequired = Convert.ToBoolean(token.Claims.First(claim => claim.Type == "password_change_required").Value);

            if (isPasswordChangeRequired)
            {
                return(Forbid());
            }

            try
            {
                var file = Request.Form.Files[0];
                var name = Request.Form.Files[0].FileName;
                await _photoService.AddPhoto(file, id);

                return(Ok(new { message = "Upload successful" }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = "Upload failed: " + ex.Message }));
            }
        }
示例#12
0
        public async Task <IActionResult> ChangeAvatar(ChangeAvatarViewModel model)
        {
            User currentUser = await _userService.GetCurrentUserAsync(HttpContext);

            if (ModelState.IsValid && (model.ProfileId == currentUser.ProfileId || User.IsInRole("Admin")))
            {
                try
                {
                    var newAvatar = await _photoService.AddPhoto(model.Image);

                    var result = await _profileService.ChangeAvatar(model.ProfileId, newAvatar);

                    if (result.Succedeed)
                    {
                        await _photoService.Delete(Int32.Parse(result.Message));

                        return(Ok(newAvatar.Url));
                    }
                }
                catch (Exception e)
                {
                    return(BadRequest(e.Message));
                }
            }

            return(BadRequest());
        }
示例#13
0
        public async Task <IActionResult> Edit(EditUserViewModel model, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                User user = await _userManager.FindByIdAsync(model.Id);

                if (user != null)
                {
                    user.Email    = model.Email;
                    user.UserName = model.UserName;
                    user.Birthday = model.Birthday;
                    user.Sex      = model.Sex;
                    if (user.Avatar == null)
                    {
                        user.Avatar = _photoService.AddPhoto(file);
                    }

                    var result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }
                }
            }

            return(View(model));
        }
示例#14
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)));
        }
示例#15
0
        public async Task <OperationResult> Create(EventDTO eventDTO)
        {
            if (eventDTO.DateFrom == DateTime.MinValue)
            {
                eventDTO.DateFrom = DateTime.Today;
            }

            if (eventDTO.DateTo == DateTime.MinValue)
            {
                eventDTO.DateTo = DateTime.Today;
            }

            var ev = _mapper.Map <EventDTO, Event>(eventDTO);

            try
            {
                ev.Photo = await _photoService.AddPhoto(eventDTO.Photo);
            }
            catch
            {
                return(new OperationResult(false, "Invalid file", ""));
            }

            var eventCategories = eventDTO.Categories?
                                  .Select(x => new EventCategory {
                Event = ev, CategoryId = x.Id
            })
                                  .ToList();

            ev.Categories = eventCategories;

            try
            {
                var result = Db.EventRepository.Insert(ev);
                await Db.SaveAsync();

                eventDTO.Id = result.Id;
                await _mediator.Publish(new EventCreatedMessage(eventDTO));

                return(new OperationResult(true, "Create new Event", result.Id.ToString()));
            }
            catch (Exception ex)
            {
                return(new OperationResult(false, ex.Message, ""));
            }
        }
        public PhotosController(
            DataContext dataContext,
            IPhotoService photoService
            )
        {
            _context      = dataContext;
            _photoService = photoService;

            if (_context.Photos.Count() == 0)
            {
                _photoService.AddPhoto(new Photo {
                    Title = "First photo!"
                });
                _photoService.AddPhoto(new Photo {
                    Title = "second photo..."
                });
            }
        }
示例#17
0
        public IActionResult AddPhoto([FromBody] PhotoRequest request)
        {
            var result = _photoService.AddPhoto(request);

            if (String.IsNullOrEmpty(result.Error))
            {
                return(Ok(result.Id));
            }
            return(BadRequest(result.Error));
        }
        public async Task <IActionResult> PhotoSaveAsync(IFormFile photo, CancellationToken cancellationToken)
        {
            var response = await _photoService.AddPhoto(photo, cancellationToken);

            if (response.IsSuccess)
            {
                return(Ok(response));
            }
            return(BadRequest(response));
        }
示例#19
0
 public ActionResult <Photo> PostPhoto([FromBody] Photo photo)
 {
     if (ModelState.IsValid)
     {
         photo.Likes    = new List <Like>();
         photo.Comments = new List <Comment>();
         _photoService.AddPhoto(photo);
         return(Ok(photo));
     }
     return(BadRequest());
 }
示例#20
0
        public async Task <OperationResult> CreateOrUpdate(MapDto model)
        {
            if (model.Id != null)
            {
            }

            Photo icon = await _photoService.AddPhoto(model.Photo);

            if (model.Preview != null)
            {
                Photo previewIcon = await _photoService.AddPhoto(model.Preview);
            }

            var map = _unitOfWork.MapRepo.Insert(new Map()
            {
                Coordinates = model.Coordinates, WallIcon = icon
            });
            await _unitOfWork.SaveAsync();

            return(new OperationResult(true, "Ok", map.Id + " " + map.Coordinates));
        }
示例#21
0
        public async Task <ActionResult <Note> > Post(IFormCollection form)
        {
            var       userId         = HttpContext.User.GetUserId();
            ColumnDto columnToUpdate = await ColumnToUpdate(userId);

            var note = new NoteDto {
                Header = form["header"], Body = form["body"]
            };
            string accessToken = form["accessToken"];

            note.Position = new PositionDto()
            {
                Column = columnToUpdate.ColumnId
            };
            note.UserId = userId;

            IFormFile imageFile = form.Files.FirstOrDefault();

            if (imageFile != null)
            {
                NewPhoto uploadedPhoto = await _photoService.AddPhoto(accessToken, userId, imageFile);

                note.ImagePath = uploadedPhoto.Id;

                var processedPhoto = await _photoService.GetPhoto(accessToken, uploadedPhoto.Id);

                note.ImageUrl = $"{processedPhoto.BaseUrl}=w2048-h1024";
            }

            await _notesCollection.InsertOneAsync(note);

            var noteIds = columnToUpdate.NoteIds.ToList();

            noteIds.Insert(0, note.Id);
            await _columnRepository.Update(userId, columnToUpdate.ColumnId, noteIds);

            return(new ActionResult <Note>(_mapper.Map <Note>(note)));
        }
示例#22
0
        private void UpdateOldImage(Product product)
        {
            var productPhoto = _photoService.GetPhoto(product.Id);

            if (productPhoto != null)
            {
                _photoService.DeletePhoto(productPhoto);
            }
            if (product.Photo != null)
            {
                product.Photo.Product = null;
                _photoService.AddPhoto(product.Photo);
            }
        }
示例#23
0
        public async Task <IActionResult> Create(SongCreateViewModel vm)
        {
            if (!TryValidateModel(vm))
            {
                return(View(vm));
            }

            DotNetEnv.Env.Load();

            var songToDb = new Song
            {
                Title           = vm.SongTitle,
                NormalizedTitle = vm.SongTitle.ToUpper(),
                Duration        = vm.Duration,
                SongLink        = vm.Link.Replace(DotNetEnv.Env.GetString("YOUTUBE_LINK"), "")
            };

            await _songService.ChangeAlbum(vm.AlbumTitle, songToDb);

            if (songToDb.Album != null && songToDb.Album.ReleaseDate == null && vm.ReleaseDate.HasValue)
            {
                songToDb.Album.ReleaseDate = vm.ReleaseDate.Value;
            }

            if (vm.PhotoUrl != null && songToDb.Album != null)
            {
                songToDb.Album.PhotoUrl = _photoService.AddPhoto(vm.PhotoUrl);
            }

            await _songService.ChangeBand(vm.BandName, songToDb);

            await _applicationDbContext.Songs.AddAsync(songToDb);

            await _applicationDbContext.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public IActionResult AddPhoto([FromQuery] string url, [FromQuery] DateTime date)
        {
            var photo = new Photo()
            {
                Url  = url,
                Date = date
            };
            var identity = (ClaimsIdentity)User.Identity;
            var userId   = identity.FindFirst("user_id").Value;

            photo.Author = userId;
            if (_photoService.AddPhoto(photo) != null)
            {
                return(Ok(photo));
            }
            return(BadRequest());
        }
示例#25
0
        public async Task <OperationResult> CreateOrUpdate(TankDto model)
        {
            if (model.Id != null)
            {
            }

            Photo icon = await _photoService.AddPhoto(model.Photo);

            var tank = _unitOfWork.TankRepo.Insert(new Tank()
            {
                Icon = icon
            });

            await _unitOfWork.SaveAsync();

            return(new OperationResult(true, "", ""));
        }
示例#26
0
        public async Task <IActionResult> ProfileSettings(ProfileSettingsViewModel model, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                User user = await _userManager.FindByIdAsync(model.Id);

                if (user != null)
                {
                    user.Email    = model.Email;
                    user.UserName = model.UserName;
                    user.Birthday = model.Birthday;
                    user.Sex      = model.Sex;
                    if (file != null)
                    {
                        if (model.AvatarExist)
                        {
                            _photoService.UpdatePhoto((int)user.AvatarId, file);
                        }
                        else
                        {
                            user.Avatar = _photoService.AddPhoto(file);
                        }
                    }
                    else if (file == null && model.AvatarExist && HttpContext.Request.Form.Keys.Contains("file"))
                    {
                        _photoService.DeletePhotoFromUser(user);
                    }

                    var result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }
                }
            }

            return(View(model));
        }
        public ActionResult Receive(HttpPostedFileBase fileData, string atlasId)
        {
            var remark = String.Empty;

            if (String.IsNullOrEmpty(atlasId))
            {
                remark = @"图册编号为空,请确认后再提交";
                var data = new { state = false, description = remark };
                return(Json(data));
            }
            if (fileData != null && fileData.ContentLength > 0)
            {
                var atlasGuid = new Guid(atlasId);
                var temp      = _atlasService.GetAtlasById(atlasGuid);
                if (temp == null)
                {
                    remark = String.Format("未能根据编号[{0}]找到该分享图册", atlasId);
                    var data = new { state = false, description = remark };
                    return(Json(data));
                }

                const bool isWater     = false;
                const bool isThumbnail = true;
                var        upload      = new UploadUtility(StoreAreaForUpload.ForGallery);
                var        photoDto    = upload.PictureSaveAs(fileData, isThumbnail, isWater, false);
                if (photoDto.PhotoId == Guid.Empty)
                {
                    var data = new { state = false, description = photoDto.Remark };
                    return(Json(data, JsonRequestBehavior.AllowGet));
                }

                photoDto.AtlasId = atlasGuid;
                photoDto.Remark  = @"暂无描述...";
                _photoService.AddPhoto(photoDto);
                var result = new { state = true, item = photoDto };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }

            var error = new { state = false, description = @"无上传的图片" };

            return(Json(error, JsonRequestBehavior.AllowGet));
        }
示例#28
0
        public async Task <AnswerModel> UploadPhoto(IFormFile photo, int answerId, string source)
        {
            var path      = $"answers/{answerId}/{photo.FileName}";
            var container = "quizbuilder-photos";

            var photoPath = await _storageService.UploadFileAsync(photo, container, path);

            var newPhoto = new Photo {
                Description = Path.GetFileNameWithoutExtension(photo.FileName),
                Path        = path,
                Extension   = Path.GetExtension(photo.FileName),
                Source      = source
            };

            await _photoService.AddPhoto(newPhoto);

            var answer = await _answerService.UpdatePhotoAsync(newPhoto.Id, answerId);

            return(_mapper.Map <AnswerModel>(answer));
        }
示例#29
0
        public IActionResult AddPhoto(SendFileDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var addStatus = photoService.AddPhoto(dto).Status;

            switch (addStatus)
            {
            case SendFileStatus.FileInvalid:
                return(BadRequest());

            case SendFileStatus.Ok:
                return(NoContent());

            default:
                return(StatusCode(500));
            }
        }
示例#30
0
        public ActionResult Create(HttpPostedFileBase upload, UserPhotoModel model)
        {
            if (upload != null)
            {
                if (IsImage(upload))
                {
                    //string fileName = System.IO.Path.GetFileName(upload.FileName);
                    Directory.CreateDirectory(Server.MapPath("/Content/UserPhotos/" + User.Identity.GetUserId() + "/"));
                    string address = Server.MapPath("/Content/UserPhotos/" + User.Identity.GetUserId() + "/" + Guid.NewGuid().ToString() + "." + upload.FileName.Substring(upload.FileName.LastIndexOf(".") + 1));
                    upload.SaveAs(address);

                    _photoService.AddPhoto(new UserPhotoBLL()
                    {
                        PhotoAddress = @"\" + address.Replace(Request.PhysicalApplicationPath, String.Empty),
                        UserId       = User.Identity.GetUserId(),
                        Description  = model.Description
                    });
                    return(RedirectToAction("Photos"));
                }
            }
            return(View());
        }