public Models.User GetOrAdd(Models.User user) { string userName = user.UserName; Models.User existingUser = GetByUserName(userName); if (existingUser != null) { return(existingUser); } else { user.Id = System.Guid.NewGuid().ToString("B"); this.context.Users.Add(user); return(user); } }
public async Task <IActionResult> CreatePhoto([FromForm] PhotoResource photoResource) { if (photoResource != null && !string.IsNullOrEmpty(photoResource.Name) && photoResource.FileToUpload != null) { var photo = this.mapper.Map <PhotoResource, Models.Photo>(photoResource); var fileToUpload = photoResource.FileToUpload; photo.FilePath = await this.photoUploadService.UploadPhoto(fileToUpload, this.uploadsFolderPath); var dimensions = await this.photoRepository.GetImageDimensions(fileToUpload); photo.Height = dimensions.Height; photo.Width = dimensions.Width; string imageFilePath = Path.Combine(this.uploadsFolderPath, photo.FilePath); var boxDicts = this.objectDetectionService.DetectObjectsFromImages(new List <string>() { imageFilePath }, this.uploadsFolderPath, this.outputFolderPath); var labels = boxDicts[imageFilePath].Select(b => b.Label); if (labels.Any()) { var categories = this.categoryRepository.GetByNames(labels); photo.PhotoCategories = categories.Select(cat => new Models.PhotoCategory() { Category = cat, Photo = photo }).ToList(); } var currentUser = new Models.User() { UserName = User.FindFirstValue(ClaimTypes.Name) }; if (photoResource.Album != null && photoResource.Album.Id > 0) { var newAlbum = await this.albumRepository.GetAsync(photoResource.Album.Id, false); if (newAlbum != null) { photo.Album = newAlbum; } else { return(BadRequest()); } } else { photo.Album = null; } photo.Author = this.userRepository.GetOrAdd(currentUser); this.photoRepository.Add(photo); await this.unitOfWork.CompleteAsync(); return(Ok(mapper.Map <Models.Photo, PhotoResource>(photo))); } else { return(BadRequest()); } }