public async Task <IActionResult> Create(AddBookDto model)
        {
            _logger.LogDebug("Attempting to create book resource from @{model}", model);

            if (model == null)
            {
                _logger.LogError("Could not create book resource because the @{model} was null", model);
                return(RedirectToAction("Error", "Errors"));
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }

            var book = new Book()
            {
                Title       = model.Title,
                Author      = model.Author,
                Rating      = model.Rating,
                DateRead    = model.DateRead,
                Description = model.Description,
                ImagePath   = null,
                DateCreated = DateTime.Now
            };

            if (model.Image != null)
            {
                book.ImagePath = _imageService.GenerateImagePath(Path.GetFileName(model.Image.FileName));
            }

            try
            {
                if (book.ImagePath != null)
                {
                    if (_imageService.TrySaveAndResizeImage(model.Image, BookImageSize, book))
                    {
                        _logger.LogDebug("The @{model.Image} for @{book} was successfully saved and resized", model.Image, book);
                    }
                    else
                    {
                        _logger.LogError("Failed to create @{book} because the @{model.Image} image was not created", book, model.Image);
                        ViewBag.CreateImageError = "We were not able to create the book image due to an error, please try again or submit your book entry without the image";
                        return(View());
                    }
                }

                await _bookRepository.CreateAsync(book);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Something went wrong while trying to create @{book} resource from @{model}", book, model);
                return(RedirectToAction("Error", "Errors"));
            }

            _logger.LogDebug("Successfully created @{book} resource created from @{model}", book, model);
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #2
0
        /// <summary>
        /// Seeds the database with default book data
        /// </summary>
        public bool TrySeed()
        {
            _logger.LogDebug("Attempting to seed database");

            if (_context.Books.Any())
            {
                _logger.LogDebug("The database already contains data and does not need to be seeded");
                return(false);
            }

            var defaultDataFilePath = Path.Combine(_hosting.ContentRootPath, "Data", "BookData.json");
            var books = File.ReadAllText(defaultDataFilePath);

            var bookImports = JsonConvert.DeserializeObject <List <Book> >(books);

            var oldImageDirectory = Path.Combine(_hosting.WebRootPath, "images", "userResources");

            if (Directory.Exists(oldImageDirectory))
            {
                Directory.Delete(oldImageDirectory, true);
            }

            for (int i = 0; i < bookImports.Count; i++)
            {
                var imagePath       = bookImports[i].ImagePath;
                var sourceImagePath = Path.Combine(_hosting.WebRootPath, "images", "appResources", imagePath);

                if (!Directory.Exists(Path.GetDirectoryName(sourceImagePath)))
                {
                    _logger.LogError("The Directory for the @{sourceImagePath} does not exist", sourceImagePath);
                    return(false);
                }

                var generatedImagePath = _bookImageService.GenerateImagePath(imagePath);
                var targetImagePath    = Path.Combine(_hosting.WebRootPath, "images", "userResources", generatedImagePath);

                Directory.CreateDirectory(Path.GetDirectoryName(targetImagePath));

                File.Copy(sourceImagePath, targetImagePath);
                _logger.LogDebug("File was copied from @{sourcePath} to @{targetPath}", sourceImagePath, targetImagePath);

                bookImports[i].ImagePath = generatedImagePath;
            }

            _context.Books.AddRange(bookImports);
            _context.SaveChanges();

            if (bookImports.Count() != _context.Books.Count())
            {
                _logger.LogError("Could not seed the database with all of the Seed Data");
                return(false);
            }

            _logger.LogDebug("Seeded the database with default book data from @{filePath}", defaultDataFilePath);
            return(true);
        }