Example #1
0
        public async Task <IActionResult> Create([FromBody] BookCreateModel book)
        {
            if (ModelState.IsValid)
            {
                BookResultModel response = await this.bookService.CreateBook(book.Name, book.Description, book.ImageUrl, book.Author, book.ReleaseDate, book.Categories);

                if (!response.Success)
                {
                    FailedResponseModel badResponse = new FailedResponseModel()
                    {
                        Errors = response.Errors
                    };

                    return(BadRequest(badResponse));
                }

                BookSuccessResponseModel successResponse = new BookSuccessResponseModel()
                {
                    Name = response.Name
                };

                return(Ok(successResponse));
            }

            return(BadRequest(new FailedResponseModel {
                Errors = ModelState.Values.SelectMany(x => x.Errors.Select(y => y.ErrorMessage))
            }));
        }
Example #2
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));
 }
Example #3
0
        public async Task CreateAsync(BookCreateModel bookCreateModel, int[] storesId)
        {
            var book = new Book()
            {
                Name        = bookCreateModel.Name,
                Author      = bookCreateModel.AuthorId == 0 ? null : await _authorService.GetAsync(bookCreateModel.AuthorId),
                ISBN        = bookCreateModel.ISBN,
                Price       = bookCreateModel.Price,
                Description = bookCreateModel.Description
            };

            if (bookCreateModel.Image != null)
            {
                if (bookCreateModel.Image.Length > 0)
                {
                    book.Cover = ImageToByte(bookCreateModel.Image);
                }
            }

            await _context.AddAsync(book);

            //Сначало сохраняем, чтобы записать сущность в бд
            await _context.SaveChangesAsync();

            // Передаем Id сущностей Store и создаем многосвязную таблицу Books - Stores (RelStoreBook)
            if (storesId.Length != 0)
            {
                var createdBook = await _context.Books
                                  .FirstOrDefaultAsync(x => x.Name == book.Name && x.Author == book.Author && x.ISBN == book.ISBN);

                await CreateOrUpdateBookStores(createdBook, storesId);

                await _context.SaveChangesAsync();
            }
        }
Example #4
0
        public async Task <ActionResult> Create([FromBody] BookCreateModel model)
        {
            if (Request.Cookies.ContainsKey("role"))
            {
                var role = Request.Cookies["admin"];
                if (role != "admin")
                {
                    return(BadRequest("Error"));
                }
            }
            else
            {
                return(BadRequest("Error"));
            }

            try
            {
                using var service = _bookService;
                var result = await service.AddBook(model);

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest($"Error {e}"));
            }
        }
Example #5
0
        public int Post(BookCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception("Form is invalid.");
            }

            return(_bookService.AddBook(model, _userManager.GetUserId(User)));
        }
        public IHttpActionResult Post(BookCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var id = _bookStoreManager.Create(model);

            return(Created(Url.Content($"~/edit/{id}"), id));
        }
Example #7
0
        public static ServiceBook CreateModelToServiceBook(this BookCreateModel bkm)
        {
            ServiceBook sb = new ServiceBook()
            {
                AgeCategory      = bkm.AgeCategory,
                FirstPublication = bkm.PublishDate,
                Name             = bkm.Name
            };

            return(sb);
        }
Example #8
0
        public async Task <IActionResult> Post(BookCreateModel book)
        {
            var bookEntity = _mapper.Map <Book>(book);

            if (!_bookValidationService.IsBookBelongsToCategory(bookEntity))
            {
                return(BadRequest($"Can not save book. Category by id {book.CategoryId} was not found."));
            }
            await _bookService.Create(bookEntity);

            return(Ok());
        }
Example #9
0
        public ActionResult EditBook(int id, BookCreateModel bookModel)
        {
            Book updatedBook = new Book(id, bookModel.Title, bookModel.Price, bookModel.Author);
            int  retCode     = _repository.UpdateBook(id, updatedBook);

            if (retCode != 0) // error
            {
                return(NotFound());
            }

            return(NoContent());
        }
Example #10
0
        public ActionResult <Book> AddBook(BookCreateModel bookModel)
        {
            Book inputBook = new Book(bookModel.Title, bookModel.Price, bookModel.Author);
            Book addedBook = _repository.AddBook(inputBook);

            if (addedBook == null)
            {
                return(StatusCode(500));
            }

            return(CreatedAtAction("ListBooks", new { id = addedBook.Id }, addedBook));
        }
Example #11
0
        public async Task <IActionResult> Create()
        {
            BookCreateModel book = new BookCreateModel();

            foreach (var w in _writerRepository.Get())
            {
                book.Writers.Add(new SelectListItem {
                    Value = w.Id.ToString(), Text = $"{w.LastName} {w.FirstName}"
                });
            }
            return(View(book));
        }
        public IHttpActionResult Post([FromBody] BookCreateModel bookModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var newBook  = Mapper.Map <Book>(bookModel);
            var id       = _bookRepository.Add(newBook);
            var location = new Uri(Request.RequestUri + "/" + id);

            return(Created(location, id));
        }
Example #13
0
        public IActionResult Create()
        {
            var categories = this.categoryService.AllCategories().Select(x => x.Name).ToList();
            var authors    = this.authorService.AllAuthors().Select(x => x.Name).ToList();

            var model = new BookCreateModel
            {
                Categories = categories,
                Authors    = authors
            };

            return(View(model));
        }
Example #14
0
        public async Task AddBookAsync(BookCreateModel bookCreateModel)
        {
            string path = "/img/" + bookCreateModel.ImgFile.FileName;

            using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
            {
                await bookCreateModel.ImgFile.CopyToAsync(fileStream);
            }

            bookCreateModel.ImgPath = path;

            await _bookService.AddBookAsync(_mapper.Map <BookDTO>(bookCreateModel));
        }
Example #15
0
        public async Task <IActionResult> Post([FromBody] BookCreateModel cm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            cm.IPAddress = HttpContext.Connection.RemoteIpAddress.ToString();

            var vm = await this.service.AddAsync(cm);

            return(Ok(vm));
        }
Example #16
0
        public Book Update(long id, BookCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(null);
            }

            var entity = _repository.Get(id);

            entity.Title    = model.Title;
            entity.AuthorId = model.AuthorId;

            _repository.Update(entity);
            return(entity);
        }
        public IHttpActionResult Post([FromUri] BookCreateModel book)
        {
            IHttpActionResult badRequest;

            if (!this.IsModelValid(ModelState, book, out badRequest))
            {
                return(badRequest);
            }

            var bookEntity = Mapper.Map <Book>(book);

            Database <Book> .Create(bookEntity);

            var bookReadModel = Mapper.Map <BookReadModel>(bookEntity);

            return(CreatedAtRoute("DefaultApi", new { controller = "books", id = bookReadModel.Id }, bookReadModel));
        }
Example #18
0
        public Book Post(BookCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(null);
            }

            var entity = new Book
            {
                Title       = model.Title,
                AuthorId    = model.AuthorId,
                CreatedDate = DateTime.Now
            };

            _repository.Insert(entity);
            return(entity);
        }
        public void AddBook_BadArgument_Exception()
        {
            var bookCreateModel = new BookCreateModel
            {
                Name        = "SomeBookName",
                BookUrl     = "SomeBookUrl",
                ImageUrl    = "SomeImageUrl",
                Description = "SomeBookDescription",
                Year        = 2020,
                Authors     = new List <string>(),
                Genres      = new List <string>()
            };

            _mockBookRepository.Setup(w => w.GetAll()).ReturnsAsync(_books);
            _mockBookRepository.Setup(w => w.Add(It.IsAny <Book>())).ReturnsAsync(_book);
            using var bookService = new BookService(_mockBookRepository.Object, _mapper);
            Assert.ThrowsAsync <CustomException>(() => bookService.AddBook(bookCreateModel));
        }
        public void AddBook_GoodArgument_Success()
        {
            var bookCreateModel = new BookCreateModel
            {
                Name        = "SomeBookName1",
                BookUrl     = "SomeBookUrl",
                ImageUrl    = "SomeImageUrl",
                Description = "SomeBookDescription",
                Year        = 2020,
                Authors     = new List <string>(),
                Genres      = new List <string>()
            };

            _mockBookRepository.Setup(w => w.GetAll()).ReturnsAsync(_books);
            _mockBookRepository.Setup(w => w.Add(It.IsAny <Book>())).ReturnsAsync(_book);
            using var bookService = new BookService(_mockBookRepository.Object, _mapper);
            Assert.That(bookService.AddBook(bookCreateModel).Result, Is.TypeOf <string>());
        }
        public async Task <IActionResult> Create(BookCreateModel collection)
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);

            if (ModelState.IsValid)
            {
                await m_bookService.Create(collection);

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                ViewBag.PublishersList = await GetPublishersSelectList();

                ViewBag.AuthorsList = await GetAuthorsSelectList();

                return(View(collection));
            }
        }
Example #22
0
        public ActionResult Create([FromBody] BookCreateModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Title) ||
                    string.IsNullOrEmpty(model.Author))
                {
                    var result = new ContentResult();
                    result.Content = "Invalid data.";
                    return(result);
                }

                _bookService.Create(model.Title, model.Author);

                return(Redirect("/Home/index"));
            }
            catch
            {
                return(View());
            }
        }
        public int Create(BookCreateModel model)
        {
            var book = new DbBook();

            book.ISBN        = model.ISBN;
            book.Image       = model.Image;
            book.Pages       = model.Pages;
            book.PublishDate = model.PublishDate;
            book.Publisher   = model.Publisher;
            book.Title       = model.Title;

            var id     = _bookRepository.Create(book);
            var author = new DbAuthor();

            author.BookId    = id;
            author.FirstName = model.AuthorFirstName;
            author.LastName  = model.AuthorLastName;
            _authorRepository.Create(author);

            return(id);
        }
 public ActionResult Create(BookCreateModel model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             int userID = (int)Profile["ID"];
             int id = Book.SaveBook(model, userID, Server);
             return RedirectToAction("Details", new {id = id});
         }
         var bcm = Book.GetBookCreateModel();
         model.AuthorList = bcm.AuthorList;
         model.GenreList = bcm.GenreList;
         model.TagList = bcm.TagList;
         return View(model);
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         return View("Error");
     }
 }
Example #25
0
        /// <summary>
        /// 예약 추가
        /// </summary>
        /// <param name="cm"></param>
        /// <returns></returns>
        public async Task <BookViewModel> AddAsync(BookCreateModel cm)
        {
            try
            {
                cm.Id = Guid.NewGuid();
                var em = Mapper.Map <Book>(cm);
                var ok = await base.AddAsync(em);

                if (ok)
                {
                    IncreaseBookCache(em);
                    return(await OrderAsync(em));
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message, cm);
                throw;
            }

            return(null);
        }
Example #26
0
        public async Task <IActionResult> Create([Bind("Numberofpages,Genre,Booklanguage,Bookname,Plot,AuthorName")] BookCreateModel books)
        {
            if (ModelState.IsValid)
            {
                var maxId = 0;
                if (_context.Books.Count() == 0)
                {
                    maxId = 0;
                }
                else
                {
                    maxId = _context.Books.Max(x => x.Id);
                }
                var book = new Books();
                book.Id              = ++maxId;
                book.Numberofpages   = books.Numberofpages;
                book.Genre           = books.Genre;
                book.Booklanguage    = books.Booklanguage;
                book.Bookname        = books.Bookname;
                book.Plot            = books.Plot;
                book.Numberofsamples = 0;
                _context.Add(book);
                await _context.SaveChangesAsync();

                //dodadi red vo writtenby tabelata
                var author = _context.Authors.Where(x => x.Authorname == books.AuthorName).FirstOrDefault();
                var row    = new Writtenby();
                row.Authorid = author.Id;
                row.Bookid   = book.Id;
                _context.Add(row);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewBag.UserId   = _httpContextAccessor.HttpContext.Request.Cookies["id"];
            ViewBag.UserName = _httpContextAccessor.HttpContext.Request.Cookies["username"];
            ViewBag.UserRole = _httpContextAccessor.HttpContext.Request.Cookies["userrole"];
            return(View(books));
        }
Example #27
0
        public async Task <string> AddBook(BookCreateModel bookCreateModel)
        {
            if (bookCreateModel == null || bookCreateModel.Name.IsNullOrEmpty() || bookCreateModel.Description.IsNullOrEmpty())
            {
                throw new CustomException("Некоректные данные");
            }
            var books = await _bookRepository.GetAll();

            if (books == null)
            {
                throw new ServerException("Сервер вернул null");
            }
            if (books.Any(w => string.Equals(w.Name, bookCreateModel.Name)))
            {
                throw new CustomException("Книга с таким именем уже есть");
            }
            var result = await _bookRepository.Add(_mapper.Map <Book>(bookCreateModel));

            if (result == null)
            {
                throw new ServerException("Сервер вернул null");
            }
            return(result.Id);
        }
Example #28
0
        public async Task <IActionResult> Create([Bind("Title, Description, Image")] BookCreateModel bookCreateModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(bookCreateModel));
            }

            var value = Guid.NewGuid();
            var path  = Path.Combine(_env.WebRootPath, "Books/" + value);

            if (bookCreateModel.Image.Length > 0)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                using (var fileStream = new FileStream(Path.Combine(path, bookCreateModel.Image.FileName), FileMode.Create))
                {
                    await bookCreateModel.Image.CopyToAsync(fileStream);
                }
            }

            var absolutePath = "~/Books/" + value;

            _repository.CreateBook(
                Book.CreateBook(
                    bookCreateModel.Title,
                    bookCreateModel.Description,
                    absolutePath,
                    bookCreateModel.Image.FileName
                    )
                );

            return(RedirectToAction(nameof(Index)));
        }
Example #29
0
        public static int SaveBook(BookCreateModel model, int userID, HttpServerUtilityBase server)
        {
            int id      = manager.bookService.AddBook(model.CreateModelToServiceBook());
            var book    = manager.bookService.GetBookById(id);
            var authors = manager.authorService.GetAllAuthors().ToList();

            //Adding authors
            foreach (var author in model.Authors?.Select(authorID => authors.FirstOrDefault(e => e.ID == authorID)).Where(e => e != null) ?? new List <ServiceAuthor>())
            {
                manager.authorService.AddAuthorBook(author, book);
            }

            var genres = manager.listService.GetAllGenres().ToList();

            //Adding genres
            foreach (var genre in model.Genres?.Select(genreID => genres.FirstOrDefault(e => e.ID == genreID)).Where(genre => genre != null) ?? new List <ServiceGenre>())
            {
                manager.listService.AddBookGenre(book, genre);
            }

            var tags = manager.listService.GetAllTags().ToList();

            //Adding tags
            foreach (var tag in model.Tags?.Select(tagID => tags.FirstOrDefault(e => e.ID == tagID)).Where(tag => tag != null) ?? new List <ServiceTag>())
            {
                manager.listService.AddBookTag(book, tag);
            }
            //Adding files
            if (model.Files != null)
            {
                foreach (var file in model.Files)
                {
                    if (file != null)
                    {
                        string filepath = File.SaveFile(server, file, "~/App_Data/Uploads/Files/");
                        manager.bookService.AddFile(book,
                                                    new ServiceFile {
                            BookID = id, Path = filepath, Format = Path.GetExtension(filepath)
                        });
                    }
                }
            }

            if (model.Covers != null)
            {
                //Adding covers
                foreach (var cover  in model.Covers)
                {
                    if (cover != null)
                    {
                        string filepath = File.SaveFile(server, cover, "~/App_Data/Uploads/Covers/Books");
                        manager.bookService.AddCover(book,
                                                     new ServiceCover {
                            BookID = id, ImagePath = filepath
                        });
                    }
                }
            }

            //Adding content
            if (model.Content != null)
            {
                manager.commentService.AddContent(new ServiceContent()
                {
                    BookID = book.ID,
                    Text   = model.Content,
                    UserID = userID
                });
            }

            return(id);
        }
Example #30
0
        public ActionResult Create(BookCreateModel model, bool downloadable)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            var userId = this.User.Identity.GetUserId();

            var book = new Book
            {
                Title        = model.Title,
                Description  = model.Description,
                RequredMoney = model.RequredMoney
            };

            if (model.File != null)
            {
                int idx = model.File.FileName.LastIndexOf('.');
                if (idx == -1)
                {
                    this.ModelState.AddModelError(string.Empty, "File must have an extention!");
                    return(this.View());
                }

                var fileName      = model.File.FileName.Substring(0, idx);
                var fileExtention = model.File.FileName.Substring(idx + 1);

                if (!Regex.IsMatch(fileExtention, ValidationConstants.FileExtentionRegex))
                {
                    this.ModelState.AddModelError(string.Empty, "File extention not supported!");
                    return(this.View());
                }

                using (var memory = new MemoryStream())
                {
                    model.File.InputStream.CopyTo(memory);
                    var content = memory.GetBuffer();

                    book.BookFile = new BookFile
                    {
                        Downloadable  = downloadable,
                        Content       = content,
                        Name          = fileName,
                        FileExtension = fileExtention
                    };
                }
            }

            var user = this.users.GetUser(this.User.Identity.GetUserId());

            var creationResult = this.books.Create(book);

            this.users.BindBookAndUser(user.Id, creationResult.Id);

            this.TempData.Clear();

            this.TempData[GlobalConstants.MessageNameSuccess] = "You've successfuly created a book!";

            return(this.RedirectToAction("Details", new { id = creationResult.Id }));
        }