public async Task <IActionResult> AddBook(int userId,
                                                  [FromForm] BookForCreationDto bookForCreationDto)
        {
            //Checking if the userId matches the currently logged in User's ID
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            if (userFromRepo != null)
            {
                //Adding the Book to the User's library and to the database
                var book = _mapper.Map <Book>(bookForCreationDto);
                var read = new Read();
                read.Book = book;
                read.User = userFromRepo;

                _repo.Add(book);
                _repo.Add(read);
                //Uploading the Book's picture to the cloud
                _repo.UploadPictureToCloud(book, bookForCreationDto.File);

                //Saving changes
                if (await _repo.SaveAll())
                {
                    var bookToReturn = _mapper.Map <BookDetailedViewDto>(book);
                    return(CreatedAtRoute("GetBookDetail", new { bookId = book.Id }, bookToReturn));
                }
            }
            //if the User was not found
            return(BadRequest("Could not add the book"));
        }
Beispiel #2
0
 private void PopulateBooksIfNoneExist()
 {
     if (!_bookRepository.GetBooks().Any())
     {
         _bookRepository.Add(new Book("Red October", new Author("Tom", "Clancy", 79), new DateTime(1995, 1, 1)));
         _bookRepository.Add(new Book("White Fang", new Author("Jack", "London", 99), new DateTime(1911, 1, 1)));
     }
 }
Beispiel #3
0
        public ActionResult SubmitWordSeries([FromBody] SubmitWordsViewModel model)
        {
            var userId = GetUser().Id;

            if (model.Book.Id == 0)
            {
                model.Book.Id = _bookRepository.Add(new Book
                {
                    Name             = model.Book.Name,
                    TargetLanguageId = model.Book.TargetLanguageId,
                    BaseLanguageId   = model.Book.BaseLanguageId
                }, userId).Id;

                if (model.Chapter != null)
                {
                    model.Chapter.Id = _chapterRepository.Add(new Chapter
                    {
                        Name   = model.Chapter.Name,
                        BookId = model.Book.Id,
                    }, userId).Id;
                }
            }

            if (model.Chapter?.Id == 0)
            {
                model.Chapter.Id = _chapterRepository.Add(new Chapter
                {
                    Name   = model.Chapter.Name,
                    BookId = model.Book.Id,
                }, userId).Id;
            }
            _wordRepository.SubmitWordSeries(new SubmitWordsModel
            {
                BaseLanguage = new NameIdModel {
                    Id = model.BaseLanguage.Id, Name = model.BaseLanguage.Name
                },
                TargetLanguage = new NameIdModel {
                    Id = model.TargetLanguage.Id, Name = model.TargetLanguage.Name
                },
                Book = model.Book != null ? new Book {
                    Id = model.Book.Id
                } : new Book(),
                Chapter = model.Chapter != null ? new Chapter {
                    Id = model.Chapter.Id
                } : new Chapter(),
                Words = model.Words.Select(x => new FormWords
                {
                    Base = new FormWord {
                        Value = x.Base.Value
                    },
                    Targets = x.Targets.Select(y => new FormWord {
                        Value = y.Value
                    }).ToList()
                }).ToList()
            }, userId);
            return(Ok());
        }
Beispiel #4
0
        public async Task <Book> Add(Book book)
        {
            if (_bookRepository.Search(b => b.Name == book.Name).Result.Any())
            {
                return(null);
            }

            await _bookRepository.Add(book);

            return(book);
        }
        public void Index_Will_Redirect_To_Books_Controller_For_Surprise_Books()
        {
            peopleRepository.Add(testPerson);
            bookRepository.Add(testBook);

            var randomEntityPickerMock = new Mock <IRandomEntityPicker>();

            randomEntityPickerMock.Setup(picker => picker.GetRandomEntityType()).Returns(typeof(Book));

            var result = (RedirectToRouteResult)controller.RandomItem(randomEntityPickerMock.Object);

            Assert.That(result.RouteValues["controller"], Is.EqualTo("Books"));
        }
Beispiel #6
0
 public ActionResult AddBook(GlobalBook item, HttpPostedFileBase file)
 {
     if (ModelState.IsValid)
     {
         try
         {
             var fileName = Guid.NewGuid().ToString();
             var path     = Path.Combine(Server.MapPath("~/App_Data/BooksBase/"), fileName);
             file.SaveAs(path);
             item.Created = DateTime.UtcNow;
             item.DataId  = fileName;
             var result = _repository.Add(item, User.Identity.Name);
             if (result == null)
             {
                 ViewBag.Message = "We have this position in Book List";
                 return(View("AddBook"));
             }
         }
         catch (Exception)
         {
             ViewBag.Message = "Upload failed";
             return(View("AddBook"));
         }
         ViewBag.Message = "Upload successful";
         return(RedirectToAction("GetAllMyBooks", new GlobalBook()));
     }
     return(View(item));
 }
Beispiel #7
0
        public ActionResult Upload(UploadViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.File != null)
                {
                    // The image must be uploaded to the images folder in wwwroot
                    // To get the path of the wwwroot folder we are using the inject
                    // HostingEnvironment service provided by ASP.NET Core
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Books");
                    // To make sure the file name is unique we are appending a new
                    // GUID value and and an underscore to the file name
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.File.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    // Use CopyTo() method provided by IFormFile interface to
                    // copy the file to wwwroot/images folder
                    model.File.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                var user = new Book()
                {
                    BookName    = model.Name,
                    Link        = uniqueFileName,
                    Description = model.Description
                };
                repository.Add(user);
                return(RedirectToAction("Index"));
            }


            return(View(model));
        }
Beispiel #8
0
        public async Task <Result> Handle(CreateBookCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();

            if (request.IsValid())
            {
                if (await _bookRepository.GetById(request.ID) == null)
                {
                    await _bookRepository.Add(
                        new Book(request.ID, request.Title, request.Author, request.Category, request.Quantity, request.Price)
                        );
                }
                else
                {
                    var message = "The Book ID already exists.";
                    await _mediator.Publish(new Notification(message), cancellationToken);

                    result.AddError(message);
                }
            }
            else
            {
                await _mediator.Publish(new Notification(request.ValidationResult), cancellationToken);

                result.AddErrors(GetErrors(request));
            }
            return(result);
        }
        public IActionResult Post([FromBody] BookViewModel record)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var book = _mapper.Map <Book>(record);
                // TODO: Add insert logic here
                book.CreatedBy   = User.Identity.Name;
                book.CreatedDate = DateTime.UtcNow;
                book.Timestamp   = DateTime.UtcNow;

                var id = _repo.Add(book);

                _logger.LogInformation(LoggingEvents.Critical, $"Added BookID: {id} - Title:{record.Title}", id);

                return(Ok(id));
            }
            catch (Exception ex)
            {
                _logger.LogError(LoggingEvents.Error, ex, $"ERROR: Could not add book: {record.Title}");
            }

            return(BadRequest("Book information could not be saved"));
        }
Beispiel #10
0
 public async Task <IActionResult> Create(BookCreateModel model)
 {
     if (ModelState.IsValid)
     {
         Book book = new Book
         {
             Caption       = model.Caption,
             PublishedDate = model.PublishedDate,
             WriterBooks   = new List <WriterBook>()
         };
         foreach (var id in model.WriterIds)
         {
             book.WriterBooks.Add(new WriterBook {
                 WriterId = id
             });
         }
         _bookRepository.Add(book);
         return(RedirectToAction("Index"));
     }
     foreach (var w in _writerRepository.Get())
     {
         model.Writers.Add(new SelectListItem {
             Value = w.Id.ToString(), Text = $"{w.LastName} {w.FirstName}"
         });
     }
     return(View(model));
 }
        public void AddBook(BookModel bookModel)
        {
            var book = bookModel.ToBook();

            _iBookRepository.Add(book);
            _iBookRepository.SaveChanges();
        }
Beispiel #12
0
        public IHttpActionResult AddBook(BookModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("model is not valid"));
            }

            var sameBook = _bookRepository.FirstOrDefault(b => b.Name == model.Name && b.Author == model.Author);

            if (sameBook != null)
            {
                return(BadRequest("the same book is aready exist"));
            }

            var book = new Book()
            {
                Name   = model.Name,
                Author = model.Author
            };

            if (model.PublishingYear.HasValue && model.PublishingYear <= DateTime.Now.Year)
            {
                book.PublishingYear = model.PublishingYear;
            }

            if (string.IsNullOrEmpty(model.PublishingHouse))
            {
                book.PublishingHouse = model.PublishingHouse;
            }

            _bookRepository.Add(book);

            return(Ok());
        }
        public ActionResult Create(BookAuthor bookAuthor)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string fileName = UploadFile(bookAuthor.File) ?? string.Empty;
                    if (bookAuthor.AuthorId == -1)
                    {
                        ViewBag.msg = "Please select Author";
                        return(View(GetAllAuthors()));
                    }
                    Book book = new Book
                    {
                        Description = bookAuthor.Description,
                        Title       = bookAuthor.Title,
                        Id          = bookAuthor.Id,
                        Author      = authorRepository.find(bookAuthor.AuthorId),
                        ImgUrl      = fileName
                    };

                    bookRepository.Add(book);
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    return(View());
                }
            }
            else
            {
                ModelState.AddModelError("", "You have to fill required feild");
                return(View(GetAllAuthors()));
            }
        }
        private void SaveBook(DownloadItemDataModel item, BookSummary bookSummary, IBookSummaryParser previewGenerator, IsolatedStorageFile storeForApplication)
        {
            using (var imageStorageFileStream = new IsolatedStorageFileStream(CreateImagesPath(item), FileMode.Create, storeForApplication))
            {
                previewGenerator.SaveImages(imageStorageFileStream);
            }

            previewGenerator.SaveCover(item.BookID.ToString());

            var book = CreateBook(item, bookSummary);

            try
            {
                _bookService.Add(book);
                TokensTool.SaveTokens(book, previewGenerator);
                book.Hidden = book.Trial;
                _bookService.Save(book);
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
            catch (Exception)
            {
                _bookService.Remove(book.BookID);
                throw;
            }
        }
Beispiel #15
0
        public async Task <IActionResult> AddBook(Book book)
        {
            _bookRepository.Add(book);
            await _bookRepository.Save();

            return(CreatedAtAction(nameof(GetBookById), new { id = book.Id }, book));
        }
Beispiel #16
0
        public Book SaveBook([FromUri] Guid userId, [FromBody] Book book)
        {
            if (book == null)
            {
                throw new APIInputException()
                      {
                          ErrorCode        = (int)HttpStatusCode.BadRequest,
                          ErrorDescription = "Bad Request. Provide valid book object. Object can't be null.",
                          HttpStatus       = HttpStatusCode.BadRequest
                      }
            }
            ;
            if (userId == null || userId == Guid.Empty)
            {
                throw new APIInputException()
                      {
                          ErrorCode        = (int)HttpStatusCode.BadRequest,
                          ErrorDescription = "Bad Request. Provide valid userId guid. Can't be empty guid.",
                          HttpStatus       = HttpStatusCode.BadRequest
                      }
            }
            ;
            BookRepository.Add(book);
            BookRepository.SaveChanges();
            var result = BookRepository.GetBookByID(book.Id);

            if (result != null)
            {
                return(result);
            }
            else
            {
                throw new APIDataException(2, "Error Saving Book", HttpStatusCode.NotFound);
            }
        }
Beispiel #17
0
        public void AdicionandoLivro()
        {
            var shelf = new Shelf
            {
                Number = 500
            };


            _authors.Add(new Author()
            {
                Name = "Allan Boladao"
            });
            _authors.Add(new Author()
            {
                Name = "Ludwig Von Mises"
            });

            var book = new Book
            {
                Name    = "Como nao destruir o pais",
                Shelf   = shelf,
                Authors = _authors
            };

            var books = _bookRepository.Get();

            _bookRepository.Add(book);
            _uow.Commit();
        }
Beispiel #18
0
        public async Task <ActionResult <Response> > CreateBook(BookModel model)
        {
            var(category, author) = await _repository.GetCategoryAndAuthor(model.AuthorId, model.CategoryId);

            if (category == null || author == null)
            {
                return(NotFound(
                           ResponseHelper
                           .CreateResponse("Author ou categoria não foram encontrados", model)
                           ));
            }

            var book = model.ToEntity(category, author);

            if (book.Invalid)
            {
                return(BadRequest(
                           ResponseHelper
                           .CreateResponse("Informações inválidas para criar um livro", book.Notifications)
                           ));
            }

            if (await _repository.BookExist(book))
            {
                return(BadRequest(
                           ResponseHelper
                           .CreateResponse("O livro já existe", book.Notifications)
                           ));
            }

            _repository.Add(book);

            return(Ok(ResponseHelper.CreateResponse("Livro cadastrado com sucesso", (BookModel)book)));
        }
 public void AddBook(string bookName, User user)
 {
     bookRepository.Add(new Book()
     {
         Id = Guid.NewGuid(), User = user, Name = bookName
     });
 }
        public ActionResult <BookDto> Add([FromBody] BookCreateDto bookCreateDto)
        {
            if (bookCreateDto == null)
            {
                return(BadRequest());
            }

            //Book toAdd = _mapper.Map<Book>(bookCreateDto);

            Book toAdd = new Book {
                Author = bookCreateDto.Author, Description = bookCreateDto.Description, Genre = bookCreateDto.Genre, Read = bookCreateDto.Read, Title = bookCreateDto.Title
            };

            _bookRepository.Add(toAdd);

            if (!_bookRepository.Save())
            {
                throw new Exception("Creating an item failed on save.");
            }

            Book newItem = _bookRepository.GetSingle(toAdd.Id);

            return(CreatedAtRoute(nameof(GetSingle), new { id = newItem.Id },
                                  _mapper.Map <BookDto>(newItem)));
        }
    //Constructor where injection is done
    //...

    public void ExampleMethod()
    {
        //...some logic
        _authorRepository.Update(author);
        //author gets updated
        _bookRepository.Add(newBook);
        //new book is saved
    }
Beispiel #22
0
        public static Book AddOneBook(IBookRepository bookRepository)
        {
            var book = Books(ObjectId.GenerateNewId().ToString())[0];

            bookRepository.Add(book);

            return(book);
        }
Beispiel #23
0
        public Book Add(Book item)
        {
            var addedBook = bookRepository.Add(item);

            bookRepository.SaveChanges();

            return(addedBook);
        }
Beispiel #24
0
 public int?Post([FromBody] Book value)
 {
     if (bookRepo.Add(value))
     {
         return(value.ID);
     }
     return(null);
 }
Beispiel #25
0
 public ActionResult Create(Book book)
 {
     if (ModelState.IsValid)
     {
         repository.Add(book);
     }
     return(RedirectToAction("Index"));
 }
        public BookViewModel AddBook(BookViewModel bookRequest)
        {
            var book = _mapper.Map <Book>(bookRequest);

            var addedBook = _bookRepository.Add(book);

            return(_mapper.Map <BookViewModel>(addedBook));
        }
Beispiel #27
0
        public void Add(BookDto bookDto)
        {
            var book = _mapper.Map <Book>(bookDto);

            book.Id = Guid.NewGuid();

            _bookRepository.Add(book);
        }
Beispiel #28
0
        public async Task <BookResponse> AddBookAsync(AddBookRequest request)
        {
            var item   = _bookMapper.Map(request);
            var result = _bookRepository.Add(item);
            await _bookRepository.UnitOfWork.SaveChangesAsync();

            return(_bookMapper.Map(result));
        }
        public async Task <CreateBookCommandResult> Handle(CreateBookManualCommand request, CancellationToken cancellationToken)
        {
            var categories = await _categoryRepository.GetAllByIdAsync(request.CategoriesIds);

            if (!categories.Any())
            {
                return(new CreateBookCommandResult(false, new[] { "Requested category/s not found" }));
            }

            var authors = await _authorRepository.GetAllByIdAsync(request.AuthorsIds);

            if (!authors.Any())
            {
                return(new CreateBookCommandResult(false, new[] { "Requested category/s not found" }));
            }

            var book = new Domain.Book(request.Title,
                                       request.Description, request.Isbn10,
                                       request.Isbn13, request.LanguageId,
                                       request.PublisherId, request.PageCount,
                                       request.Visibility, request.PublishedDate);

            foreach (var category in categories)
            {
                book.AddCategory(category);
            }

            foreach (var author in authors)
            {
                book.AddAuthor(author);
            }

            var result = _bookRepository.Add(book);

            if (await _bookRepository.UnitOfWork.SaveChangesAsync(cancellationToken) < 1)
            {
                return(new CreateBookCommandResult(false, new[] { "Error occured during saving Book" }));
            }


            var bookResult = _mapper.Map <CommandBookDto>(result);

            var bookResultEvent = _mapper.Map <CreateBook>(result);

            bookResultEvent.Language = result.LanguageId > 0
                ? _mapper.Map <LanguageDto>(await _languageRepository.FindByIdAsync(result.LanguageId ?? 0))
                : null;
            bookResultEvent.Publisher = result.LanguageId > 0
                ? _mapper.Map <PublisherDto>(await _publisherRepository.FindByIdAsync(result.PublisherId ?? 0))
                : null;


            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri($"queue:{EventBusConstants.CreateBookQueue}"));

            await endpoint.Send(bookResultEvent, cancellationToken);

            return(new CreateBookCommandResult(true, bookResult));
        }
        public void AddBook(params Book[] books)
        {
            if (Exists(books[0].BookFile.FullPathAndFileNameWithExtension))
            {
                return;
            }

            _bookRepository.Add(books);
        }