public async Task <UserDto> UploadUserFoto(string email, FileDto model) { var repoUser = _contextManager.CreateRepositiry <IUserRepo>(); var user = repoUser.GetUserByEmail(email); if (user == null) { throw new ValidationException("User not found"); } if (!(user.ServerFileName == null)) { await _uploadService.Delete(user.ServerFileName, model.Container); } var guidStr = Guid.NewGuid().ToString(); var serverFileName = "userId-" + user.Id.ToString() + "-" + guidStr; model.ServerFileName = serverFileName; var filePath = await _uploadService.Upload(model); user.OriginalFileName = model.File.FileName; user.FotoUrl = filePath.Url; user.ServerFileName = filePath.ServerFileName + model.File.FileName; _contextManager.Save(); return(_mapper.Map <UserDto>(user)); }
public async Task <EventDto> UploadEventFoto(int EventId, FileDto model) { var repo = _contextManager.CreateRepositiry <IEventRepo>(); var eventF = repo.GetById(EventId); _subscriptionService.CheckSubscription(eventF.CompanyId); if (eventF == null) { throw new ValidationException("Event not found"); } if (!(eventF.ServerFileName == null)) { await _uploadService.Delete(eventF.ServerFileName, model.Container); } var guidStr = Guid.NewGuid().ToString(); var serverFileName = "userId-" + eventF.Id.ToString() + "-" + guidStr; model.ServerFileName = serverFileName; var filePath = await _uploadService.Upload(model); eventF.OriginalFileName = model.File.FileName; eventF.FotoUrl = filePath.Url; eventF.ServerFileName = filePath.ServerFileName + model.File.FileName; _contextManager.Save(); return(_mapper.Map <EventDto>(eventF)); }
public async Task <SubscriptionRatesDto> UploadSubFoto(int subId, FileDto model) { var repo = _contextManager.CreateRepositiry <ISubscriptionRatesRepo>(); var sub = repo.GetById(subId); if (sub == null) { throw new ValidationException("Subscription not found"); } if (!(sub.ServerFileName == null)) { await _uploadService.Delete(sub.ServerFileName, model.Container); } var guidStr = Guid.NewGuid().ToString(); var serverFileName = "subId-" + sub.Id.ToString() + "-" + guidStr; model.ServerFileName = serverFileName; var filePath = await _uploadService.Upload(model); sub.OriginalFileName = model.File.FileName; sub.FotoUrl = filePath.Url; sub.ServerFileName = filePath.ServerFileName + model.File.FileName; _contextManager.Save(); return(_mapper.Map <SubscriptionRatesDto>(sub)); }
public async Task <CompanyDto> UploadCompanyFoto(int CompanyId, FileDto model) { _subscriptionService.CheckSubscription(CompanyId); var repo = _contextManager.CreateRepositiry <ICompanyRepo>(); var company = repo.GetById(CompanyId); if (company == null) { throw new ValidationException("Company not found"); } if (!(company.ServerFileName == null)) { await _uploadService.Delete(company.ServerFileName, model.Container); } var guidStr = Guid.NewGuid().ToString(); var serverFileName = "compId-" + company.Id.ToString() + "-" + guidStr; model.ServerFileName = serverFileName; var filePath = await _uploadService.Upload(model); company.OriginalFileName = model.File.FileName; company.FotoUrl = filePath.Url; company.ServerFileName = filePath.ServerFileName + model.File.FileName; _contextManager.Save(); return(_mapper.Map <CompanyDto>(company)); }
public async Task <ObjectResult> Carousel(Enumeration.ContentItemType contentType, int contentId, int id, List <SlideViewModel> slides) { var block = await _blockRepository.Get(id); if (!(block is CarouselBlock carousel)) { return(new NotFoundObjectResult(null)); } List <string> photoPaths = carousel.Slides.Select(s => s.PhotoPath).ToList(); await TryUpdateModelAsync(carousel, string.Empty, c => c.Order, c => c.LinkText, c => c.LinkPath); UpdateCarouselSlides(carousel, slides); for (var i = 0; i < slides.Count; i++) { ValidateImageExtension(slides[i].Image, $"Slides[{i}].Image"); } if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } foreach (var slide in carousel.Slides) { if (slide.Image != null) { if (slide.PhotoPath != null) { await _uploadService.Delete(slide.PhotoPath); } slide.PhotoPath = await _uploadService.Upload(slide.Image, "/images/uploads"); } } SetTypeId(block, contentType, contentId); carousel.Active = true; carousel.LastModified = DateTime.UtcNow; await _blockRepository.Update(carousel); var newPaths = carousel.Slides.Select(s => s.PhotoPath).ToList(); foreach (var photoPath in photoPaths) { if (!newPaths.Contains(photoPath)) { await _uploadService.Delete(photoPath); } } return(new OkObjectResult(null)); }
public IActionResult Delete(int id) { int uid = int.Parse(this.User.FindFirstValue(ClaimTypes.Name)); _uploadService.Delete(id, uid); return(Ok()); }
private void DeleteUploads(List <HtmlUpload> htmlUploads, IUnitOfWork unitOfWork) { foreach (HtmlUpload htmlUpload in htmlUploads) { if (HtmlUploadIsImage(htmlUpload)) { _uploadService.Delete(htmlUpload.ImageTenantId.Value, htmlUpload.ThumbnailImageUploadId.Value, GetHtmlUploadStorageHierarchy(htmlUpload.ElementId), unitOfWork); _uploadService.Delete(htmlUpload.ImageTenantId.Value, htmlUpload.PreviewImageUploadId.Value, GetHtmlUploadStorageHierarchy(htmlUpload.ElementId), unitOfWork); _uploadService.Delete(htmlUpload.ImageTenantId.Value, htmlUpload.ImageUploadId.Value, GetHtmlUploadStorageHierarchy(htmlUpload.ElementId), unitOfWork); } if (HtmlUploadIsUpload(htmlUpload)) { _uploadService.Delete(htmlUpload.UploadTenantId.Value, htmlUpload.UploadId.Value, GetHtmlUploadStorageHierarchy(htmlUpload.ElementId), unitOfWork); } } }
public async Task <IActionResult> EditPost(int?id) { var download = await _downloadRepository.Get(id ?? 0); if (download == null) { return(NotFound()); } await TryUpdateModelAsync(download, string.Empty, d => d.Title, d => d.Description, d => d.File, d => d.TagIds); if (download.File != null && download.File.Length < 1) { ModelState.AddModelError(nameof(download.File), "Filesize too small"); } if (!ModelState.IsValid) { return(View(download)); } if (download.File != null) { if (download.LinkPath != null) { await _uploadService.Delete(download.LinkPath); } download.LinkPath = await _uploadService.Upload(download.File, "/files", Path.GetFileNameWithoutExtension(download.File.FileName)); } download.DownloadTags.RemoveAll(dt => !(download.TagIds?.Contains(dt.TagId) ?? false)); download.DownloadTags.AddRange( download.TagIds?.Except(download.DownloadTags.Select(dt => dt.TagId)) .Select(tagId => new DownloadTag { Download = download, TagId = tagId }) ?? new List <DownloadTag>()); try { download.LastModified = DateTime.UtcNow; await _downloadRepository.Update(download); } catch (DbUpdateConcurrencyException) { if (!await DownloadExists(download.Id)) { return(NotFound()); } throw; } return(RedirectToAction(nameof(Index))); }
public Response <FileModel> Delete(string path) { var response = _upload.Delete(path); return(new Response <FileModel> { Success = true, Message = MessageConstant.Delete }); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Image,LogoPath,Link")] Customer customer) { if (id != customer.Id) { return(NotFound()); } if (customer.Image != null) { if (!(new[] { ".png", ".jpg", ".jpeg" }).Contains(Path.GetExtension(customer.Image.FileName)?.ToLower())) { ModelState.AddModelError(nameof(customer.Image), "Invalid image type, only png and jpg images are allowed"); } if (customer.Image.Length == 0) { ModelState.AddModelError(nameof(customer.Image), "Filesize too small"); } } if (!ModelState.IsValid) { return(View(customer)); } try { if (customer.Image != null) { if (customer.LogoPath != null) { await _uploadService.Delete(customer.LogoPath); } customer.LogoPath = await _uploadService.Upload(customer.Image, "/images/uploads/customers", customer.Name); } await _customerRepository.Update(customer); } catch (DbUpdateConcurrencyException) { if (!await CustomerExists(customer.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); }
/// <summary> /// Updates a page (not including zones and elements). /// </summary> /// <param name="page">Updated page details.</param> /// <param name="unitOfWork">Unit of work.</param> public void Update(Page page, IUnitOfWork unitOfWork = null) { // If we don't have a unit of work in place, create one now so that we can rollback all changes in case of failure IUnitOfWork localUnitOfWork = unitOfWork == null?_unitOfWorkFactory.CreateUnitOfWork() : null; // Do the page update try { // Set updated date to now page.Updated = DateTime.UtcNow; // Perform validation (including checking that all or none of the image upload properties are specified) _pageValidator.ValidateUpdate(page); // Get current page Page currentPage = _pageRepository.Read(page.TenantId, page.PageId, unitOfWork ?? localUnitOfWork); // Master page determines what can and can't be updated MasterPage masterPage = _masterPageRepository.Read(page.TenantId, page.MasterPageId, unitOfWork ?? localUnitOfWork); // Commit page images? if (page.ImageUploadId.HasValue && currentPage.ImageUploadId != page.ImageUploadId) { _uploadService.Commit(page.ImageTenantId.Value, page.ThumbnailImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); _uploadService.Commit(page.ImageTenantId.Value, page.PreviewImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); _uploadService.Commit(page.ImageTenantId.Value, page.ImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); } // Update page details _pageRepository.Update(page, unitOfWork ?? localUnitOfWork); // Update page tags? if (masterPage.Taggable) { _pageRepository.UpdateTags(page, unitOfWork ?? localUnitOfWork); } // Delete old page images? if (currentPage.ImageUploadId.HasValue && currentPage.ImageUploadId != page.ImageUploadId) { _uploadService.Delete(currentPage.ImageTenantId.Value, currentPage.ThumbnailImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentPage.ImageTenantId.Value, currentPage.PreviewImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentPage.ImageTenantId.Value, currentPage.ImageUploadId.Value, GetPageImageStorageHierarchy(), unitOfWork ?? localUnitOfWork); } // Commit work if local unit of work in place if (localUnitOfWork != null) { localUnitOfWork.Commit(); } } catch (ValidationErrorException) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw; } catch (Exception ex) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw new ValidationErrorException(new ValidationError(null, ApplicationResource.UnexpectedErrorMessage), ex); } }
public async Task <IActionResult> EditPost(int?id) { var solution = await _solutionRepository.Get(id ?? 0, true); if (solution == null) { return(new NotFoundObjectResult(null)); } // Bind POST variables Title, CustomerId, Image and TagIds to the model. await TryUpdateModelAsync(solution, string.Empty, s => s.Title, s => s.CustomerIds, s => s.Image, s => s.TagIds, c => c.SharingDescription, c => c.Summary); if (solution.Image != null) { if (!(new[] { ".png", ".jpg", ".jpeg" }).Contains(Path.GetExtension(solution.Image.FileName)?.ToLower())) { ModelState.AddModelError(nameof(solution.Image), "Invalid image type, only png and jpg images are allowed"); } if (solution.Image.Length == 0) { ModelState.AddModelError(nameof(solution.Image), "Filesize too small"); } } if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } if (solution.Image != null) { if (solution.PhotoPath != null) { await _uploadService.Delete(solution.PhotoPath); } solution.PhotoPath = await _uploadService.Upload(solution.Image, "/images/uploads/solutions"); } solution.SolutionTags.RemoveAll(ct => !(solution.TagIds?.Contains(ct.TagId) ?? false)); solution.SolutionTags.AddRange(solution.TagIds?.Except(solution.SolutionTags.Select(ct => ct.TagId)) .Select(tagId => new SolutionTag { Solution = solution, TagId = tagId }) ?? new List <SolutionTag>()); solution.CustomerSolutions.RemoveAll(ct => !(solution.CustomerIds?.Contains(ct.CustomerId) ?? false)); solution.CustomerSolutions.AddRange(solution.CustomerIds?.Except(solution.CustomerSolutions.Select(ct => ct.CustomerId)) .Select(customerId => new CustomerSolution { Solution = solution, CustomerId = customerId }) ?? new List <CustomerSolution>()); try { solution.LastModified = DateTime.UtcNow; await _solutionRepository.Update(solution); } catch (DbUpdateConcurrencyException) { if (!await SolutionExists(solution.Id)) { return(new NotFoundObjectResult(null)); } throw; } return(new ObjectResult(solution.Id)); }
public void Update(IElementSettings settings, IUnitOfWork unitOfWork = null) { // If we don't have a unit of work in place, create one now so that we can rollback all changes in case of failure IUnitOfWork localUnitOfWork = unitOfWork == null?_unitOfWorkFactory.CreateUnitOfWork() : null; // Begin work try { // Validate slides CarouselSettings carouselSettings = (CarouselSettings)settings; foreach (CarouselSlide slide in carouselSettings.Slides) { _carouselValidator.ValidateSlide(slide); } // Get current carousel settings CarouselSettings currentCarouselSettings = (CarouselSettings)New(settings.TenantId); currentCarouselSettings.ElementId = settings.ElementId; _carouselRepository.Read(currentCarouselSettings, unitOfWork ?? localUnitOfWork); // Get slides to delete (i.e. slides that were in current settings, but not in the new settings) // Get slides with updated images List <CarouselSlide> slidesToDelete = new List <CarouselSlide>(); List <CarouselSlide> slidesWithUpdatedImages = new List <CarouselSlide>(); List <CarouselSlide> currentSlidesWithUpdatedImages = new List <CarouselSlide>(); Dictionary <long, CarouselSlide> slidesById = carouselSettings.Slides.Where(s => s.CarouselSlideId != 0).GroupBy(s => s.CarouselSlideId).ToDictionary(u => u.Key, u => u.First()); foreach (CarouselSlide currentSlide in currentCarouselSettings.Slides) { if (!slidesById.ContainsKey(currentSlide.CarouselSlideId)) { slidesToDelete.Add(currentSlide); } else { CarouselSlide slide = slidesById[currentSlide.CarouselSlideId]; if (slide.ImageUploadId != currentSlide.ImageUploadId) { slidesWithUpdatedImages.Add(slide); currentSlidesWithUpdatedImages.Add(currentSlide); } } } // Get new slides List <CarouselSlide> slidesToCreate = carouselSettings.Slides.Where(s => s.CarouselSlideId == 0).ToList(); // Commit new images slidesToCreate.AddRange(slidesWithUpdatedImages); foreach (CarouselSlide slide in slidesToCreate) { _uploadService.Commit(slide.ImageTenantId, slide.ThumbnailImageUploadId, GetCarouselSlideStorageHierarchy(slide.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Commit(slide.ImageTenantId, slide.PreviewImageUploadId, GetCarouselSlideStorageHierarchy(slide.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Commit(slide.ImageTenantId, slide.ImageUploadId, GetCarouselSlideStorageHierarchy(slide.ElementId), unitOfWork ?? localUnitOfWork); } // Update database _carouselRepository.Update((CarouselSettings)settings, unitOfWork ?? localUnitOfWork); // Delete uploads that are no longer required slidesToDelete.AddRange(currentSlidesWithUpdatedImages); foreach (CarouselSlide currentSlide in slidesToDelete) { _uploadService.Delete(currentSlide.ImageTenantId, currentSlide.ThumbnailImageUploadId, GetCarouselSlideStorageHierarchy(currentSlide.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentSlide.ImageTenantId, currentSlide.PreviewImageUploadId, GetCarouselSlideStorageHierarchy(currentSlide.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentSlide.ImageTenantId, currentSlide.ImageUploadId, GetCarouselSlideStorageHierarchy(currentSlide.ElementId), unitOfWork ?? localUnitOfWork); } // Commit work if local unit of work in place and return result if (localUnitOfWork != null) { localUnitOfWork.Commit(); } } catch (ValidationErrorException) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw; } catch (Exception ex) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw new ValidationErrorException(new ValidationError(null, ApplicationResource.UnexpectedErrorMessage), ex); } finally { if (localUnitOfWork != null) { localUnitOfWork.Dispose(); } } }
public async Task <ObjectResult> EditPost(int?id) { var newsItem = await _newsItemRepository.Get(id ?? 0, true); if (newsItem == null) { return(new NotFoundObjectResult(null)); } // Bind POST variables Title, CustomerId, Image and TagIds to the model. await TryUpdateModelAsync(newsItem, string.Empty, c => c.Title, c => c.Image, c => c.TagIds, c => c.SharingDescription); if (newsItem.Image != null && newsItem.Image?.Length == 0) { ModelState.AddModelError(nameof(newsItem.Image), "Filesize too small"); } if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } if (newsItem.Image != null) { var extension = Path.GetExtension(newsItem.Image.FileName); if (extension != ".jpg" && extension != ".png" && extension != ".jpeg") { ModelState.AddModelError(nameof(newsItem.Image), "The uploaded file was not an image."); return(new BadRequestObjectResult(ModelState)); } if (newsItem.PhotoPath != null) { await _uploadService.Delete(newsItem.PhotoPath); } newsItem.PhotoPath = await _uploadService.Upload(newsItem.Image, "/images/uploads/newsitems"); } newsItem.NewsItemTags.RemoveAll(ct => !(newsItem.TagIds?.Contains(ct.TagId) ?? false)); newsItem.NewsItemTags.AddRange(newsItem.TagIds?.Except(newsItem.NewsItemTags.Select(ct => ct.TagId)) .Select(tagId => new NewsItemTag { NewsItem = newsItem, TagId = tagId }) ?? new List <NewsItemTag>()); try { newsItem.LastModified = DateTime.UtcNow; await _newsItemRepository.Update(newsItem); } catch (DbUpdateConcurrencyException) { if (!await NewsItemExists(newsItem.Id)) { return(new NotFoundObjectResult(null)); } throw; } return(new ObjectResult(newsItem.Id)); }
//[Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrator")] public IActionResult Delete([FromBody] DeleteFileModel model) { return(_codeFactory.GetStatusCode(_service.Delete(model))); }
public void Update(IElementSettings settings, IUnitOfWork unitOfWork = null) { // If we don't have a unit of work in place, create one now so that we can rollback all changes in case of failure IUnitOfWork localUnitOfWork = unitOfWork == null?_unitOfWorkFactory.CreateUnitOfWork() : null; // Begin work try { // Validate slides AlbumSettings albumSettings = (AlbumSettings)settings; foreach (AlbumPhoto photo in albumSettings.Photos) { _albumValidator.ValidatePhoto(photo); } // Get current album settings AlbumSettings currentAlbumSettings = (AlbumSettings)New(settings.TenantId); currentAlbumSettings.ElementId = settings.ElementId; _albumRepository.Read(currentAlbumSettings, unitOfWork ?? localUnitOfWork); // Get photos to delete (i.e. photos that were in current settings, but not in the new settings) // Get photos with updated images List <AlbumPhoto> photosToDelete = new List <AlbumPhoto>(); List <AlbumPhoto> photosWithUpdatedImages = new List <AlbumPhoto>(); List <AlbumPhoto> currentPhotosWithUpdatedImages = new List <AlbumPhoto>(); Dictionary <long, AlbumPhoto> photosById = albumSettings.Photos.Where(p => p.AlbumPhotoId != 0).GroupBy(s => s.AlbumPhotoId).ToDictionary(u => u.Key, u => u.First()); foreach (AlbumPhoto currentPhoto in currentAlbumSettings.Photos) { if (!photosById.ContainsKey(currentPhoto.AlbumPhotoId)) { photosToDelete.Add(currentPhoto); } else { AlbumPhoto photo = photosById[currentPhoto.AlbumPhotoId]; if (photo.ImageUploadId != currentPhoto.ImageUploadId) { photosWithUpdatedImages.Add(photo); currentPhotosWithUpdatedImages.Add(currentPhoto); } } } // Get new photos List <AlbumPhoto> photosToCreate = albumSettings.Photos.Where(s => s.AlbumPhotoId == 0).ToList(); // Commit new images photosToCreate.AddRange(photosWithUpdatedImages); foreach (AlbumPhoto photo in photosToCreate) { _uploadService.Commit(photo.ImageTenantId, photo.ThumbnailImageUploadId, GetAlbumPhotoStorageHierarchy(photo.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Commit(photo.ImageTenantId, photo.PreviewImageUploadId, GetAlbumPhotoStorageHierarchy(photo.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Commit(photo.ImageTenantId, photo.ImageUploadId, GetAlbumPhotoStorageHierarchy(photo.ElementId), unitOfWork ?? localUnitOfWork); } // Update database _albumRepository.Update((AlbumSettings)settings, unitOfWork ?? localUnitOfWork); // Delete uploads that are no longer required photosToDelete.AddRange(currentPhotosWithUpdatedImages); foreach (AlbumPhoto currentPhoto in photosToDelete) { _uploadService.Delete(currentPhoto.ImageTenantId, currentPhoto.ThumbnailImageUploadId, GetAlbumPhotoStorageHierarchy(currentPhoto.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentPhoto.ImageTenantId, currentPhoto.PreviewImageUploadId, GetAlbumPhotoStorageHierarchy(currentPhoto.ElementId), unitOfWork ?? localUnitOfWork); _uploadService.Delete(currentPhoto.ImageTenantId, currentPhoto.ImageUploadId, GetAlbumPhotoStorageHierarchy(currentPhoto.ElementId), unitOfWork ?? localUnitOfWork); } // Commit work if local unit of work in place and return result if (localUnitOfWork != null) { localUnitOfWork.Commit(); } } catch (ValidationErrorException) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw; } catch (Exception ex) { if (localUnitOfWork != null) { localUnitOfWork.Rollback(); } throw new ValidationErrorException(new ValidationError(null, ApplicationResource.UnexpectedErrorMessage), ex); } finally { if (localUnitOfWork != null) { localUnitOfWork.Dispose(); } } }