private void GetBook(string bookid) { try { var response = HttpRequest.GetHttpRequest("/book/" + bookid); var createStatus = JsonConvert.DeserializeAnonymousType(response, new { BookResult = "" }); var bytes = JsonConvert.DeserializeObject<byte[]>(createStatus.BookResult.Replace(" ", "+")); var res = Encoding.UTF8.GetString(bytes); var st = JsonConvert.DeserializeObject<BookDTO>(res); _currentBook = st; author.Text = st.Author; title.Text = st.Title; desc.Text = st.BookDescription; avatar.Text = st.AvatarURL; lang.Text = st.Language; year.Text = st.Year.ToString(); download.Text = st.DownloadURL; _id = int.Parse(bookid); selected.Text = "Current ID=" + bookid; image.Source = new BitmapImage(new Uri(avatar.Text)); } catch (Exception e) { // MessageBox.Show(e.Message); GetBook(bookid); } }
public void addBook(BookDTO book) { DbConnect db = new DbConnect(); db.sqlConnection.Open(); String query = "INSERT INTO books ( ISBN, bname, bauthor_name, `bprice`, bstock, `bstoryline`, `btype`) VALUES (" + book.ISBN1 + ",'" + book.Bname + "','" + book.BauthorName + "','" + book.Bprice + "','" + book.Bstock + "','" + book.Bstoryline + "','" + book.Btype + "')"; System.Diagnostics.Debug.WriteLine(query); MySqlCommand sqlCommand = new MySqlCommand(query, db.sqlConnection); sqlCommand.ExecuteNonQuery(); db.sqlConnection.Close(); }
public HttpResponseMessage Post([FromBody] BookModel model) { try { BookDTO bookdto = modelfactory.Parse(model); string bookID = bookmanager.AddBook(bookdto); if (bookID == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "SOMETHING WENT WRONG")); } else { return(Request.CreateResponse(HttpStatusCode.Created, "BOOK CREATED SUCCESSFULLY WITH ID : " + bookID)); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public IHttpActionResult PostBook(Book book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // New code: // Load author name db.Entry(book).Reference(x => x.Author).Load(); var dto = new BookDTO() { Id = book.Id, Title = book.Title, AuthorName = book.Author.Name }; return(CreatedAtRoute("DefaultApi", new { id = book.Id }, dto)); }
public async Task BookModelValidation_AuthorNameRequired() { //Arrange var moq = new Mock <IBookService>(); Category category = new Category() { CategoryId = 2, CategoryName = "Sports" }; //This Book does not contain Author hence it is invalid BookDTO authorIsMissing = new BookDTO() { Id = 3, Title = "Swimming Advantages", CategoryId = 2, Category = category, ISBN = 9876543210, Price = 36, DateOfPublication = "2019-03-15" }; moq.Setup(r => r.CreateBook(authorIsMissing)); var controller = new BookController(moq.Object);//pass moq object inside controller controller.ModelState.AddModelError("Author", "Required"); //Act var result = await controller.PostABook(authorIsMissing); //Assert Assert.IsType <BadRequestResult>(result); }
private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtBookName.Text) || string.IsNullOrEmpty(txtAuthor.Text) || nmQuantity.Value < 1) { lblSaveStatus.Visible = true; lblSaveStatus.Text = "Tüm alanları doldurmanız gerekiyor."; lblSaveStatus.ForeColor = Color.Red; return; } using (BookService bookService = new BookService()) { BookDTO book = new BookDTO { BookId = Convert.ToInt32(lbBooks.SelectedValue), BookName = txtBookName.Text, GenreId = Convert.ToByte(cbGenres.SelectedValue), Author = txtAuthor.Text, PublishDate = dtpPublishDate.Value, UnitsInStock = Convert.ToInt32(nmQuantity.Value), CreatedDate = Convert.ToDateTime(lblCreatedDate.Text), RecordStatusId = Convert.ToByte(cbRecordStatus.SelectedValue) }; var result = bookService.Update(book); lblSaveStatus.Visible = true; if (result) { lblSaveStatus.Text = "Kitap güncelleme başarılı"; lblSaveStatus.ForeColor = Color.Green; } else { lblSaveStatus.Text = "Kitap güncellemesi sırasında bir hata oluştu."; lblSaveStatus.ForeColor = Color.Red; } } }
public static void AddBook(BookDTO book) { int genreId = GetGenreId(book.Genre); int authorId = GetAuthorId(book.Author); using (var context = new BookCatalogContext()) { Book bookInDB = context.Books .SingleOrDefault(b => b.RefNumber == book.RefNumber && b.Title == book.Title && b.AuthorId == authorId); if (bookInDB == null) // add new book { Book newBook = new Book(); newBook.RefNumber = book.RefNumber; newBook.Title = book.Title; newBook.AuthorId = authorId; newBook.Price = book.Price; newBook.DatePublished = book.DatePublished; newBook.Description = book.Description; newBook.Genres = new[] { context.Genres.Find(genreId) }; context.Books.Add(newBook); Console.Write($"Added book "); } else // update book { bookInDB.Price = book.Price; bookInDB.DatePublished = book.DatePublished; bookInDB.Description = book.Description; if (bookInDB.Genres.FirstOrDefault(g => g.Id == genreId) == null) { bookInDB.Genres.Add(context.Genres.Find(genreId)); } Console.Write($"Updated book "); } Console.WriteLine($"{book.Title} ({book.Author})"); context.SaveChanges(); } }
public BookDTO GetById(int Id) { BookDTO bookDTO = new BookDTO(); Book book = UoW.BookRepo.GetById(Id); if (book != null) { bookDTO = new BookDTO { Id = book.Id, Title = book.Title, bookAuthor = new AuthorDTO { Id = book.AuthorId, FirstName = book.BookAuthor.FirstName, LastName = book.BookAuthor.LastName, Description = book.BookAuthor.Description, ActiveFrom = book.BookAuthor.ActiveFrom, ActiveTo = book.BookAuthor.ActiveTo, BookCount = book.BookAuthor.BookCount, Rating = book.BookAuthor.Rating }, bookGenre = new GenreDTO { Id = book.GenreId, GenreName = book.BookGenre.GenreName, Description = book.BookGenre.Description, BookCount = book.BookGenre.BookCount, Rating = book.BookGenre.Rating, LastUpdated = book.BookGenre.LastUpdated }, Description = book.Description, DateAdded = book.DateAdded, Price = book.Price, Rating = book.Rating }; } return(bookDTO); }
public async Task <IActionResult> PostBook([FromBody] Book book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // This is not working _context.Books.Add(book); // _context.Add(book); await _context.SaveChangesAsync(); //try //{ // await _context.SaveChangesAsync(); //} //catch (DbUpdateException) //{ // if (BookExists(book.Id)) // { // return new StatusCodeResult(StatusCodes.Status409Conflict); // } // else // { // throw; // } //} _context.Entry(book).Reference(x => x.Author).Load(); var dto = new BookDTO() { Id = book.Id, Title = book.Title, // AuthorName = book.Author.Name }; return(Ok(dto)); // return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto); // return CreatedAtAction("GetBook", new { id = book.Id }, book); }
public async Task CreateBook_AddsANewBook_ToBooksTable() { //Arrange var moq = new DbContextMock <MyAppDbContext>(dummyOptions); moq.CreateDbSetMock(i => i.Books, new[] { new Book { Id = 1, Title = "Animals and Nature", Author = "James X", CategoryId = 1, ISBN = 1234567890, Price = 10, DateOfPublication = "2018-03-11" }, new Book { Id = 2, Title = "Family and Relationships", Author = "Jerry Y", CategoryId = 2, ISBN = 8876419010, Price = 20, DateOfPublication = "2019-05-18" } });//--> now we have two books inside our Books database BookDTO new_book = new BookDTO() { Id = 3, Title = "Programming Instructions", Author = "John Abcd", CategoryId = 3, ISBN = 1984657201, Price = 50, DateOfPublication = "2017-01-20" }; //Act var service = new BookService(moq.Object); await service.CreateBook(new_book);//add a new book to database //Assert Assert.Equal(3, moq.Object.Books.Count()); }
public async Task EditBook(BookDTO book) { Book chosenBook = _context.Books.Include(c => c.Category).Single(b => b.Id == book.Id); //update the properties chosenBook.Title = book.Title; chosenBook.Author = book.Author; chosenBook.CategoryId = book.CategoryId; chosenBook.ISBN = book.ISBN; chosenBook.Price = book.Price; chosenBook.DateOfPublication = book.DateOfPublication; book.Category = chosenBook.Category; await _context.SaveChangesAsync(); }
public async Task <IHttpActionResult> GetBook(string id) { try { Book book = await db.Books.FindAsync(id); if (book == null) { return(NotFound()); } BookDTO bookDTO = new BookDTO { Id = book.Id, Title = book.Title, Author = book.Author, Price = book.Price }; return(Ok(new ApiResponse(bookDTO))); } catch (Exception e) { LoggingService.Log(LoggingService.LogType.error, e.ToString(), logTag); return(InternalServerError()); } }
public async static Task <BookDTO> ToBookViewItem(this Book book, IServiceDataLookUp serviceDataLookUp) { var bookDTO = new BookDTO() { Id = book.Id, Authors = book.Authors.Select(a => a.Author.ToAuthorViewItem()).ToArray(), Isbn = book.Isbn.Value, Publisher = book.Publisher.ToPublisherViewItem(), PublicationYear = book.PublicationYear, Title = book.Title, Synopsis = book.Synopsis, NumberOfCopies = book.NumberOfCopies, CoverImageKey = book.CoverImageKey, }; var reservations = await serviceDataLookUp.LookUp(book); bookDTO.Reservations = await reservations.ToReservationViewItems(serviceDataLookUp); return(bookDTO); }
public ActionResult Create(BookViewModel model, HttpPostedFileBase uploadImage) { if (ModelState.IsValid && uploadImage != null) { byte[] imageData = null; using (var binaryReader = new BinaryReader(uploadImage.InputStream)) { imageData = binaryReader.ReadBytes(uploadImage.ContentLength); } model.Image = imageData; Mapper.Initialize(cfg => cfg.CreateMap <BookViewModel, BookDTO>()); BookDTO bookDto = Mapper.Map <BookViewModel, BookDTO>(model); bookService.Create(bookDto); return(RedirectToAction("AllBooks", "Libraryan")); } else { ModelState.AddModelError("", "Заполните все необходимые поля!"); } return(View()); }
public static bool addBook(BookDTO bo) { int codeN; using (libraryEntities db = new libraryEntities()) { Book newB = Converters.BookConverter.ConvertBookDTOToDAL(bo); newB.isDeleted = false; db.Books.Add(newB); try { db.SaveChanges(); codeN = db.Books.First(b => b.name == bo.name).codeBook; return(otekBL.addotek(codeN, Convert.ToInt32(bo.numOtakim), Convert.ToDouble(bo.price), Convert.ToInt32(bo.numOtakim))); } catch (Exception e) { return(false); } } }
internal BookDTO GetBookById(string bookId) { string query = string.Format($@"SELECT * FROM Book JOIN Book_Category USING(category_id) JOIN Author USING(author_id) WHERE book_id = '{bookId}'"); BookDTO dto = null; using (var dataSource = DataSource) { dataSource.Open(); var queryResult = QueryDataSource(query, dataSource); if (!queryResult.Read()) { throw new NotFoundException($@"Book with id {bookId} Not Found"); } dto = _adapter.ToBookDTO(queryResult); dataSource.Close(); } return(dto); }
public static AuthorDTO ToDTO(this Author author) { var authorDTO = new AuthorDTO { Id = author.GetId(), Name = author.GetName(), }; foreach (var book in author.GetBooks()) { var bookDTO = new BookDTO { Id = book.GetId(), Name = book.GetName(), }; authorDTO.BookDTOs.Add(bookDTO); } return(authorDTO); }
public IActionResult EditBook(string id) { BookDTO getedBook = _bookService.Get(id); if (getedBook == null) { return(RedirectToAction("Error")); } BookViewModel model = new BookViewModel { Id = getedBook.Id, Title = getedBook.Title.Trim(), AuthorId = getedBook.AuthorId, Rate = getedBook.Rate, Year = getedBook.Year, Description = getedBook.Description, Genre = getedBook.Genre, RatesAmount = getedBook.RatesAmount }; return(View(model)); }
public async Task <IHttpActionResult> Put(int id, Book book) { init(); if (_books.Any(b => b.Id == id)) { var oldbook = _books.FirstOrDefault(b => b.Id == id); oldbook.Genre = book.Genre; oldbook.Author = book.Author; oldbook.Price = book.Price; oldbook.Title = book.Title; oldbook.Year = book.Year; var dto = new BookDTO() { Id = book.Id, Title = book.Title, AuthorName = book.Author.Name }; return(CreatedAtRoute("DefaultApi", new { id = book.Id }, dto)); } return(NotFound()); }
public async Task <IActionResult> UpdateBook([FromBody] BookDTO book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!_bookService.BookExists(book.BookId)) { return(NotFound("Nie znaleziono książki!")); } try { _bookService.UpdateBook(book); } catch (DbUpdateConcurrencyException) { } return(Ok()); }
public IActionResult Post([FromBody] BookDTO book) { try { _service.Book(book); } catch (RentBadRequest e) { return(e.Result); } catch (RentNotFound e) { return(e.Result); } catch (Exception e) { return(StatusCode(500, e)); } return(new OkResult()); }
public ActionResult Edit(int?id) { if (id != null) { BookDTO bookDTO = bookService.GetBook(Convert.ToInt32(id)); Mapper.Initialize(cfg => cfg.CreateMap <BookDTO, BookViewModel>()); var book = Mapper.Map <BookDTO, BookViewModel>(bookDTO); List <GenreDTO> genres = genreService.GetAllGenres(); List <string> genresNames = new List <string>(); foreach (GenreDTO genre in genres) { if (genre.Name != book.Genre) { genresNames.Add(genre.Name); } } ViewBag.Genres = genresNames; return(View(book)); } return(RedirectToAction("AllBooks", "Libraryan")); }
public async Task <bool> Update(BookDTO model, string ApiUrl) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(ApiUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); var response = await client.PutAsync(ApiUrl, stringContent); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); string sonuc = (string)data; return(true); } return(false); }
public bool DeleteBook(string[] titles) { foreach (var title in titles) { BookDTO book = null; try { book = bookService.FindBookByName(title); } catch (Exception ex) { } if (book != null) { bookService.Delete(book.Id); } } return(true); }
public async Task <IHttpActionResult> PostBook(Book book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Books.Add(book); await db.SaveChangesAsync(); // New code: // Load author name db.Entry(book).Reference(x => x.Author).Load(); var dto = new BookDTO() { Id = book.Id, Title = book.Title, AuthorName = book.Author.AuthorName }; return(CreatedAtRoute("DefaultApi", new { id = book.Id }, dto)); }
public async Task <IHttpActionResult> PostBook(Book book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Books.Add(book); await db.SaveChangesAsync(); var dto = new BookDTO() { Title = book.Title, ISBN = book.ISBN, YearPublished = book.YearPublished, AuthorName = book.Author.AuthorName, AuthorSurname = book.Author.AuthorSurname }; return(CreatedAtRoute("DefaultApi", new { id = book.ISBN }, dto)); }
public async Task <IActionResult> PutBook(int id, [FromForm] BookDTO book) { try { await _bookService.UpdateBook(id, book, User); return(NoContent()); } catch (DbUpdateException) { return(BadRequest($"There is no library with id {book.LibraryId}")); } catch (KeyNotFoundException) { return(NotFound()); } catch (UnauthorizedAccessException) { return(StatusCode(403)); } }
public IEnumerable <BookDTO> GetAllBook() { var lstBookDetails = _unitOfWork.BookRepository.GetAll().ToList(); List <BookDTO> objBooklst = new List <BookDTO>(); foreach (var item in objBookRepository.GetBooks()) { BookDTO objBook = new BookDTO(); objBook.Author = item.Author; objBook.Genre = item.Genre; objBook.Price = item.Price; objBook.Title = item.Title; objBook.Year = item.Year; objBooklst.Add(objBook); } //var lstBooks = MappingProfile.Map<List<BookDetail>, List<BookDTO>>(lstBookDetails); return(objBooklst); }
/// <summary> /// Get all books in warehouse of store /// </summary> /// <returns></returns> public List <BookDTO> GetAllBooksInStore(BookDTO search) { var books = dbContext.Books.AsQueryable(); if (search != null) { if (!string.IsNullOrEmpty(search.Author)) { books = books.Where(x => x.Author.Contains(search.Author)); } if (!string.IsNullOrEmpty(search.Title)) { books = books.Where(x => x.Title.Contains(search.Title)); } if (search.PlacedDate > DateTime.MinValue) { books = books.Where(x => x.PlacedDate > search.PlacedDate); } if (search.Sale) { books = books.Where(x => x.Sale == search.Sale); } if (!string.IsNullOrEmpty(search.Type)) { books = books.Where(x => x.Type == search.Type); } } return(books.Select(x => new BookDTO { Id = x.Id, Author = x.Author, Count = x.Count, PlacedDate = x.PlacedDate, Title = x.Title, Price = x.Price, Sale = x.Sale, Type = x.Type }).ToList()); }
public IDbCommand AddBook(BookDTO book, IDbCommand command) { command.Parameters.Clear(); //This procedure will add the author and genre if it does not exist,and then with the author and genre id add the book command.CommandText = @"exec [dbo].[AddBook] @ISBN ,@Title ,@Genre ,@Author"; var parameter = command.CreateParameter(); parameter.ParameterName = "@ISBN"; parameter.DbType = DbType.String; parameter.Value = book.ISBN; command.Parameters.Add(parameter); parameter = command.CreateParameter(); parameter.ParameterName = "@Title"; parameter.DbType = DbType.String; parameter.Value = book.Title; command.Parameters.Add(parameter); parameter = command.CreateParameter(); parameter.ParameterName = "@Genre"; parameter.DbType = DbType.String; parameter.Value = book.Genre; command.Parameters.Add(parameter); parameter = command.CreateParameter(); parameter.ParameterName = "@Author"; parameter.DbType = DbType.String; parameter.Value = book.AuthorName; command.Parameters.Add(parameter); command.ExecuteNonQuery(); return(command); }
public async Task<IHttpActionResult> PostBook(Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Books.Add(book); await db.SaveChangesAsync(); db.Entry(book).Reference(x => x.Author).Load(); var bookDto = new BookDTO() { Id = book.Id, Title = book.Title, AuthorName = book.Author.Name }; return CreatedAtRoute("DefaultApi", new { id = book.Id }, bookDto); }
private void Save(object sender, RoutedEventArgs e) { var tmp = new BookDTO{BookID = _id}; if (author != null && _currentBook.Author != author.Text) { tmp.Author = author.Text; } else { tmp.Author = null; } if (title != null && _currentBook.Title != title.Text) { tmp.Title = title.Text; } else { tmp.Title = null; } if (desc != null && _currentBook.BookDescription != desc.Text) { tmp.BookDescription = desc.Text; } else { tmp.BookDescription = null; } if (lang != null && _currentBook.Language != lang.Text) { tmp.Language = lang.Text; } else { tmp.Language = null; } if (year != null && _currentBook.Year != int.Parse(year.Text)) { tmp.Year = int.Parse(year.Text); } else { tmp.Year = null; } if (avatar != null && _currentBook.AvatarURL != avatar.Text) { tmp.Author = avatar.Text; } else { tmp.Author = null; } if (download != null && _currentBook.DownloadURL != download.Text) { tmp.DownloadURL = download.Text; } else { tmp.DownloadURL = null; } var bl = JsonConvert.SerializeObject(tmp); var tl = Encoding.UTF8.GetBytes(bl); var s = JsonConvert.SerializeObject(tl).Replace('/', '-'); var uriTemplate = string.Format(_id == 0 ? "/add/?arr={0}" : "/update/?arr={0}", s); MessageBox.Show(HttpRequest.GetHttpRequest(uriTemplate)); WindowLoaded1(sender, e); }