private async Task SeedBooksAndAuthors() { Author aStugatsky = new Author() { Id = 1, Firstname = "Arkady", Lastname = "Strugatski", Bio = "He was exelent writer" }; Author bStugatsky = new Author() { Id = 2, Firstname = "Boris", Lastname = "Strugatski", Bio = "He was exelent writer and scientist" }; Author iAzymov = new Author() { Id = 3, Firstname = "Isaak", Lastname = "Azimov", Bio = "He is excellent writer and scientis" }; Book mondayStartsSaturday = new Book() { Id = 1, Title = "Monday starts saturday", Year = 1960, Isbn = "978-5-17-106224-8", Summary = "Exelent partody to scientists community", Authors = new Author[] { aStugatsky, bStugatsky } }; Book hardToBeTheGod = new Book() { Id = 2, Title = "Hard to be the God", Year = 1960, Isbn = "978-5-17-106224-8", Summary = "Another view what happens to civilizations", Authors = new Author[] { aStugatsky, bStugatsky } }; Book theGodsThemselves = new Book() { Id = 3, Title = "The Gods Themselves", Year = 1972, Isbn = "978-8-49-800851-7", Summary = "Another view what happens to civilizations", Authors = new Author[] { iAzymov } }; aStugatsky.Books = new List <Book> { mondayStartsSaturday, hardToBeTheGod }; bStugatsky.Books = new List <Book> { mondayStartsSaturday, hardToBeTheGod }; iAzymov.Books = new List <Book> { theGodsThemselves }; await _BookStore.Authors.CreateAsync(aStugatsky); await _BookStore.Authors.CreateAsync(bStugatsky); await _BookStore.Authors.CreateAsync(iAzymov); await _BookStore.Books.CreateAsync(mondayStartsSaturday); await _BookStore.Books.CreateAsync(hardToBeTheGod); await _BookStore.Books.CreateAsync(theGodsThemselves); if (!await _BookStore.SaveData()) { throw new OperationCanceledException("Failed to seed all data in the database"); } }
public async Task <IActionResult> Create([ModelBinder(typeof(BookModelBinder))] BookUpsertDTO book) { _Logger.LogTrace("Attempt to create the book"); try { if (book == null) { return(BookBadRequest("Attempt to insert empty book")); } if (!ModelState.IsValid) { return(BookBadRequest("Attempt to insert the invalid book", ModelState)); } Task <ImageData> imageUpload = null; CancellationTokenSource cts = null; if (book.ImageWasChanged) { cts = new CancellationTokenSource(); imageUpload = _ImageService.SetImage(book.Image, cts.Token, String.Empty); book.Image = String.Empty; } var user = await _SignInManager.UserManager.FindByEmailAsync(this.GetCurrentUserEmail()); Book bookRecord = _Mapper.Map <Book>(book); bookRecord.OwnerId = user.Id; var differences = DataTools.FindDifferences <BookAuthor, AuthorUpsertDTO>( bookRecord.BookAuthors, book.Authors, (old, nw) => old.AuthorId == nw.Id); foreach (var inserted in differences.InsertedItems) { Author author = await _BookStore.Authors.FindAsync(x => x.Id == inserted.Id); if (author != null) { bookRecord.BookAuthors.Add(new BookAuthor() { AuthorId = inserted.Id, Author = author, Book = bookRecord }); } else { cts?.Cancel(); return(StatusCode(StatusCodes.Status422UnprocessableEntity, "One of the book authors not exists in database, operation cancelled")); } } foreach (var removed in differences.RemovedItems) { bookRecord.BookAuthors.Remove(removed); } if (imageUpload != null) { ImageData imageData = await imageUpload; bookRecord.Image = imageData.Name; bookRecord.Thumbnail = imageData.Base64ThumbNail; } bool result = await _BookStore.Books.CreateAsync(bookRecord); result &= await _BookStore.SaveData(); if (result) { _Logger.LogInformation($"Book succesfully created, assigned id {bookRecord.Id}"); return(StatusCode(StatusCodes.Status201Created, bookRecord)); } else { return(InternalError("Failed to create book")); } } catch (AggregateException e) { _Logger.LogError(e.Flatten(), e.Flatten().Message, e.Flatten().InnerExceptions?.Select(ie => $"{ie.Message}/n{new string('-', 20)}/n{ie.StackTrace}")); return(InternalError("Failed to create the book", e)); } catch (Exception e) { _Logger.LogError(e, e.Message); return(InternalError("Failed to create bool", e)); } }
public async Task <IActionResult> Create([ModelBinder(typeof(AuthorModelBinder))] AuthorUpsertDTO author) { _Logger.LogInformation($"Author submition"); try { if (author == null) { _Logger.LogWarning($"Empty request was submited"); return(StatusCode(StatusCodes.Status400BadRequest)); } if (!ModelState.IsValid) { _Logger.LogWarning( $"Attempting to submit invalid data: {ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage).Aggregate((fm, lm) => fm + '\n' + lm)}"); return(BadRequest(ModelState)); } var user = await _SignInManager.UserManager.FindByEmailAsync(this.GetCurrentUserEmail()); var similarAuthors = await _BookStore.Authors.WhereAsync(filter : x => x.Firstname.ToLower().Equals(author.Firstname.ToLower()) && x.Lastname.ToLower().Equals(author.Firstname.ToLower()) && x.OwnerId == user.Id ); if (similarAuthors.Count > 0) { _Logger.LogWarning($"Possible duplicate for author {author.Firstname} {author.Lastname.ToUpper()}"); } Author writer = _Mapper.Map <Author>(author); writer.OwnerId = user.Id; var differences = DataTools.FindDifferences <Book, BookUpsertDTO>( writer.Books, author.Books, (o, n) => o.Id == n.Id); if (differences.InsertedItems?.Count > 0) { foreach (var newAuthorBook in differences.InsertedItems) { var authorBook = await _BookStore.Books.FindAsync(b => b.Id == newAuthorBook.Id); if (authorBook != null) { writer.AuthorBooks.Add(new BookAuthor() { Author = writer, BookId = authorBook.Id, Book = authorBook }); } else { string message = $"Failed to find book with id {newAuthorBook.Id}"; _Logger.LogWarning(message); return(StatusCode(StatusCodes.Status422UnprocessableEntity, message)); } } } var isSucceed = await _BookStore.Authors.CreateAsync(writer); isSucceed &= await _BookStore.SaveData(); if (!isSucceed) { _Logger.LogError("No records was inserted to database when creating the author"); return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to save author")); } else { _Logger.LogInformation("Author creates successfully"); return(Created("Create", _Mapper.Map <AuthorUpsertDTO>(writer))); } } catch (Exception e) { return(InternalError(e, $"Unable to create author {author.Firstname} {author.Lastname}")); } }