public async Task <IActionResult> Add(CreateAlbumViewModel model) { AlbumViewModelMapper mapper = new AlbumViewModelMapper(); PublishStatus flags = PublishStatus.PUBLISHED | PublishStatus.UNPUBLISHED; var artistNames = await _artistRepo.ListNamesAsync(flags); model.ArtistOptions = artistNames .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Selected = x.Id == model.ArtistId }).ToList(); List <CheckBoxListItem> groupOptions = (await _albumGroupRepo.ListAsync()) .Select(x => new CheckBoxListItem { Label = x.Name, Value = x.Key, IsSelected = model.Groups.Any(grp => grp.IsSelected && grp.Value == x.Key) }).ToList(); model.Groups = groupOptions; if (ModelState.IsValid) { int?createdImageId = null; if (model.CoverImage != null && model.CoverImage.Length > 0) { using (MemoryStream ms = new MemoryStream()) { await model.CoverImage.CopyToAsync(ms); ImageReferenceDetail imageRef = await _imageRepo.AddAsync(new ImageReferenceDetail { Data = ms.ToArray(), FileName = model.CoverImage.FileName, MimeType = model.CoverImage.ContentType }); if (imageRef != null) { createdImageId = imageRef.Id; } } } var result = await _albumRepo.AddAsync(mapper.Map(model, createdImageId)); await _albumGroupRepo.SetGroupsForAlbum(result.Id, model.Groups.Where(g => g.IsSelected).Select(g => g.Value).ToList()); this.SetBootstrapPageAlert("Success", "Album added", BootstrapAlertType.success); return(RedirectToAction(nameof(Index))); } else { return(View(model)); } }
public async Task <Image> AddImageAsync(AddImageData data) { var dalData = _mapper.Map <DAL.Models.AddImageData>(data); var dalResult = await _imageRepository.AddAsync(dalData); return(_mapper.Map <Image>(dalResult)); }
public async Task <IActionResult> Add(CreateArtistViewModel model) { if (ModelState.IsValid) { int?createdBioImageId = null; if (model.BioImage != null && model.BioImage.Length > 0) { using (MemoryStream ms = new MemoryStream()) { await model.BioImage.CopyToAsync(ms); ImageReferenceDetail imageRef = await _imageRepo.AddAsync(new ImageReferenceDetail { Data = ms.ToArray(), FileName = model.BioImage.FileName, MimeType = model.BioImage.ContentType }); if (imageRef != null) { createdBioImageId = imageRef.Id; } } } var result = await _artistRepo.AddAsync(new Artist { PublishedStatus = PublishStatus.UNPUBLISHED, Name = model.Name, BioText = model.BioText, Genres = model.Genres.Where(g => g.IsSelected).Select(g => g.Name).ToList(), BioImageId = createdBioImageId }); this.SetBootstrapPageAlert("Success", "Artist added", BootstrapAlertType.success); return(RedirectToAction(nameof(Index))); } else { return(View(model)); } }
public async Task <IActionResult> Add([FromHeader(Name = "ContentType")] string contentType) { int newId = 0; var result = await _repo.AddAsync(new ImageReferenceDetail { Data = new byte[0], MimeType = contentType, FileName = "" }); return(CreatedAtRoute( new { controller = "image", action = "get", id = newId }, result)); }
public async Task <ImageResponse> SaveAsync(Image image) { try { await _imageRepository.AddAsync(image); await _unitOfWork.CompleteAsync(); return(new ImageResponse(image)); } catch (Exception ex) { // Do some logging stuff return(new ImageResponse($"An error occurred when saving the image: {ex.Message}")); } }
public async Task AddImage(Guid id, Result result) { if (result.imageStringOriginal == null || result.imageStringOriginal.Length == 0) { throw new ServiceException(Exceptions.ErrorCodes.InvalidImage, "Nieprawidłowy obraz"); } if (result.imageStringProcessed == null || result.imageStringProcessed.Length == 0) { throw new ServiceException(Exceptions.ErrorCodes.InvalidImage, "Nieprawidłowy obraz"); } var guid = id; var newImage = new Image(guid, result.imageStringOriginal, result.imageStringProcessed, result.Description, result.ElapsedTime); await _imageRepository.AddAsync(newImage); }
public async Task <ImageVM> UploadAsync(string name, IFormFile file) { using var stream = new MemoryStream(); await file.CopyToAsync(stream); OptimizeImageStream(stream); var fileBytes = stream.ToArray(); var dbImage = new Image() { Name = name, Data = fileBytes }; await _imageRepository.AddAsync(dbImage); return(_mapper.Map <Image, ImageVM>(dbImage)); }
/// <summary> /// Create new image /// </summary> /// <param name="categoryId">image category</param> /// <param name="description">image description</param> /// <param name="imageFile">image name</param> /// <param name="userId">uploder id</param> /// <param name="tags">image tags</param> /// <returns>Instance of ServiceResult</returns> public virtual async Task <ServiceResult <Image> > SaveNewImageAsync(int categoryId, string description, string imageFile, string userId, List <string> tags) { //If category doesnt exist, throw InvalidRequest exception if (await categoryRepo.GetByIdAsync(categoryId) == null) { throw new InvalidRequest($"Category with id = {categoryId} doesnt exist"); } if (string.IsNullOrEmpty(imageFile)) { throw new ArgumentNullException(nameof(imageFile)); } imageFile = generator.GetUniqueImageName(imageFile); var newImage = new Image { CategoryId = categoryId, Created = DateTime.Now, Tags = tags.Select(item => new Tag { Description = item }).ToList(), Description = description ?? "", Comments = new List <Comment>(), Likes = new List <Like>(), Url = imageFile, UserId = userId, }; var serviceResult = new RequestResult <Image>(); var(instnace, message) = await imageRepo.AddAsync(newImage); if (!string.IsNullOrEmpty(message)) { return(serviceResult.BadRequest(message)); } else { return(serviceResult.GoodRequest(instnace)); } }
public async Task <ImageDto> UploadImage(IFormFile file) { var extension = _imageWriter.GetImageExtension(file); var name = await _imageWriter.UploadImage(file); var image = new Image(); var appBaseUrl = MyHttpContext.AppBaseUrl; image.Name = name; image.Extension = extension; image.Url = appBaseUrl + "/images/" + name; var resultImage = await _imageRepository.AddAsync(image); await _imageRepository.SaveAsync(); var imageDto = _mapper.Map <Image, ImageDto>(resultImage); return(imageDto); }
public async Task <Guid> AddImageAsync(string base64Image) { var imageGuid = Guid.NewGuid(); var imagePath = await CreateFullImagePathAsync(imageGuid, _config.ImagesRootDirectoryPath, GetExtension(base64Image)); await WriteImageAsync(imagePath, GetBase64Image(base64Image)); var dbImage = new Image() { Id = imageGuid, Path = imagePath }; bool imagePathSaved = await _imageRepository.AddAsync(dbImage); if (!imagePathSaved) { throw new DataAccessException($"Image path for guid: {dbImage} could not be saved!"); } return(dbImage.Id); }
private async Task LoadData() { await _keywordRepository.AddAsync(new Keyword { Value = "test" }, CancellationToken.None); await _keywordRepository.AddAsync(new Keyword { Value = "ipsum" }, CancellationToken.None); await _keywordRepository.AddAsync(new Keyword { Value = "bar" }, CancellationToken.None); await _keywordRepository.AddAsync(new Keyword { Value = "foo" }, CancellationToken.None); await _imageRepository.AddAsync(newImage, CancellationToken.None); }
public async Task <ImageApplication> AddAsync(ImageApplication entity) { var result = await _imageRepository.AddAsync(ImageMapper.Map(entity)); return(ImageMapper.Map(result)); }
private async Task LoadData() { await _imageRepository.AddAsync(newImage, CancellationToken.None); }
public async Task SynchronizeBlogPostsAsync(IBlogPostRepository sourceRepo, IBlogPostRepository destRepo, bool incremental, string overrideCursor, CancellationToken cancellationToken) { try { await _lockRepository.AcquireLockAsync("synchelperlock", 10, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), cancellationToken); _logger.LogInformation($"SynchronizeBlogPostsAsync with incremental = {incremental}"); var dropboxCursor = new CursorContainer(); if (incremental) { // Try to get a persisted cursor from our SQL database, if that's null (so we haven't got one), then we'll do a full update dropboxCursor.Cursor = overrideCursor ?? await destRepo.GetDropboxCursorAsync(cancellationToken); _logger.LogDebug($"Cursor = {dropboxCursor.Cursor}"); } var cursor = incremental && !string.IsNullOrWhiteSpace(dropboxCursor.Cursor) ? dropboxCursor : null; var sourcePosts = (await sourceRepo.GetAllAsync(cursor, cancellationToken)).ToList(); if (string.IsNullOrWhiteSpace(dropboxCursor.Cursor)) { _logger.LogInformation("No current dropbox cursor, so explicitly requesting current cursor ..."); dropboxCursor.Cursor = await _dropboxHelper.GetCurrentCursorAsync(cancellationToken); _logger.LogInformation($"Returned cursor {dropboxCursor.Cursor}"); } _logger.LogInformation($"Processing {sourcePosts.Count} source posts ..."); foreach (var sourcePost in sourcePosts) { await destRepo.AddOrUpdateAsync(sourcePost, cancellationToken); } _logger.LogInformation("Processing images ..."); var imageTasks = new List <Task>(); foreach (var sourcePost in sourcePosts) { foreach (var imageData in sourcePost.ImageData) { var imageContent = await imageData.ImageDataTask; var resizedImageFileContent = imageData.FileName.ToLower().Contains("noresize") ? imageContent : _imageResizer.Resize(imageContent, _settings.MaxResizedImageSize); imageTasks.Add(_imageRepository.AddAsync(imageData.PostFolder, imageData.FileName, resizedImageFileContent, cancellationToken)); } } await Task.WhenAll(imageTasks); if (!incremental) // Do not delete posts when in incremental mode (todo) Is this comment correct? Surely as we're reading the json file even on incremental sync, we can still delete on incremental? { var destPosts = (await destRepo.GetAllAsync(null, cancellationToken)).ToList(); var postsToDelete = destPosts.Where(d => sourcePosts.All(s => s.Id != d.Id)).ToList(); _logger.LogInformation($"Found {postsToDelete.Count} to delete out of {destPosts.Count} posts"); await destRepo.DeleteAsync(postsToDelete, cancellationToken); } await destRepo.RemoveUnusedTagsAsync(cancellationToken); _logger.LogInformation($"Saving new Dropbox cursor: {dropboxCursor.Cursor}"); await destRepo.SetDropboxCursorAsync(dropboxCursor.Cursor, cancellationToken); } finally { await _lockRepository.ReleaseLockAsync(cancellationToken); } }
private async Task LoadData() { var listOfImages = new List <Image>() { new Image { ImageId = "001", Class = Enums.Classes.Unrated, IndexSource = Enums.Sources.RedditEarthPorn, Who = "Me", Tripcode = "", ResolutionX = 1024, ResolutionY = 768, TagsString = "None", Keywords = new List <string>() { "rule34" }, DateDownloaded = DateTime.UtcNow, Reported = Enums.Reported.Unreported, Hash = "0x0", FileExtension = "png", ServerId = 0, Size = 0, Ratio = "4:3" }, new Image { ImageId = "002", Class = Enums.Classes.SafeForWork, IndexSource = Enums.Sources.RedditHiRes, Who = "Me", Tripcode = "", ResolutionX = 2560, ResolutionY = 1600, TagsString = "None", Keywords = new List <string>() { "test" }, DateDownloaded = DateTime.UtcNow, Reported = Enums.Reported.ConfirmedGood, Hash = "0x0", FileExtension = "png", ServerId = 0, Size = 0, Ratio = "16:9" }, new Image { ImageId = "003", Class = Enums.Classes.SafeForWork, IndexSource = Enums.Sources.RedditSpacePorn, Who = "Me", Tripcode = "", ResolutionX = 3840, ResolutionY = 2160, TagsString = "None", Keywords = new List <string>() { "rule34", "test" }, DateDownloaded = DateTime.UtcNow, Reported = Enums.Reported.Unreported, Hash = "0x0", FileExtension = "png", ServerId = 0, Size = 0, Ratio = "16:9" }, new Image { ImageId = "004", Class = Enums.Classes.NotSafeForWork, IndexSource = Enums.Sources.RedditNsfwWallpapers, Who = "Me", Tripcode = "", ResolutionX = 1280, ResolutionY = 720, TagsString = "None", Keywords = new List <string>() { "rule34", "test", "foobar" }, DateDownloaded = DateTime.UtcNow, Reported = Enums.Reported.Reported, Hash = "0x0", FileExtension = "png", ServerId = 0, Size = 0, Ratio = "16:9" }, }; foreach (var newImage in listOfImages) { await _imageRepository.AddAsync(newImage, CancellationToken.None); } }
public async Task AddAsync(Image image) => await _imageRepository.AddAsync(image);