public bool HasStockBy(string title) { BookDetail book = _context.BookDetails.FirstOrDefault(x => x.bookname.ToUpper() == title.ToUpper()); bool hasStock = book?.quantity > 0; return(hasStock); }
public async Task <BookDetail> UpdateAsync(int bookId, BookDetail bookDetail) { var authorsDataTable = new DataTable(); authorsDataTable.Columns.Add("Author", typeof(string)); foreach (string author in bookDetail.Authors) { authorsDataTable.Rows.Add(author); } using SqlConnection connection = new SqlConnection(_connectionString); await connection.OpenAsync(); await connection.ExecuteAsync( "Book_Modify_tr", new { BookId = bookId, NewTitle = bookDetail.Title, NewDescription = bookDetail.Description, NewPublishDate = bookDetail.PublishDate, NewAuthors = authorsDataTable.AsTableValuedParameter("AuthorTableType") }, commandType : CommandType.StoredProcedure); return(await FindDetailAsync(bookId)); }
public IActionResult Put(int id, [FromBody] BookDetail obj) { if (ModelState.IsValid) { try { var result = db.UpdateDetail(id, obj); if (result != 1) { return(NotFound()); } return(Ok(result)); } catch (Exception ex) { if (ex.GetType().FullName == "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException") { return(NotFound()); } return(BadRequest()); } } return(BadRequest()); }
private void button_Add_Click(object sender, EventArgs e) { int cur = BookList.nextBookID; Form_Item item = new Form_Item(cur); item.ReturnBook += (o, e1) => { BookDetail now = item.book; now.BookInfo.buildRawData(); now.BookPrint.buildRawData(); // 填充到 BookList BookList.Add(cur, now, true); // 重新整理内容到 ListView ListViewItem line = listView_Books.Items.Add(cur.ToString()); for (int i = 0; i < 12; i++) { line.SubItems.Add(""); } RefreshBookList(ref now, ref line); if (listView_Books.Items.Count <= 1) { SetWidthListView_Books(-2); } }; item.ShowDialog(); }
public async Task <ActionResult <BookDetail> > PostBookDetail(BookDetail bookDetail) { _context.BookDetail.Add(bookDetail); await _context.SaveChangesAsync(); return(CreatedAtAction("GetBookDetail", new { id = bookDetail.BookId }, bookDetail)); }
private static async Task FindBookByID() { Console.Clear(); Console.Write("Enter ISBN: "); string userInput = Console.ReadLine(); //HttpClient httpClient = new HttpClient(); //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token); //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"https://localhost:44331/api/Book?ISBN={userInput}"); //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token); HttpResponseMessage response = await _httpClient.GetAsync($"https://localhost:44331/api/Book?ISBN={userInput}"); if (response.IsSuccessStatusCode) { BookDetail book = await response.Content.ReadAsAsync <BookDetail>(); Console.WriteLine($"\n" + $"ISBN: {book.ISBN}"); Console.WriteLine($"Title: {book.BookTitle}"); Console.WriteLine($"Author First Name: {book.AuthorFirstName}"); Console.WriteLine($"Author Last Name: {book.AuthorLastName}"); Console.WriteLine($"Description: {book.Description}\n"); Console.WriteLine("Exchanges for this book"); foreach (ExchangeSmListItem e in book.ExchangeListItems) { Console.WriteLine(); Console.WriteLine($"exchange Id: {e.Id}\n" + $"Exchanger Rating: {e.SenderRating}\n" + $"Is book still available: {e.IsAvailable}"); } } }
// Get --single book by isbn (id) public BookDetail GetBookDetail(string ISBN) { using (var ctx = new ApplicationDbContext()) { var entity = ctx.Books.Single(e => e.ISBN == ISBN); var detailedBook = new BookDetail { ISBN = entity.ISBN, BookTitle = entity.BookTitle, AuthorFirstName = entity.AuthorFirstName, AuthorLastName = entity.AuthorLastName, GenreOfBook = entity.GenreOfBook, Description = entity.Description, NumberAvailable = entity.NumberAvailable }; foreach (Exchange exchange in entity.Exchanges) // To Display All the exchanges { detailedBook.ExchangeListItems.Add(new ExchangeSmListItem { Id = exchange.Id, IsAvailable = exchange.IsAvailable, Posted = exchange.Posted, SenderName = exchange.SenderUser.FirstName, SenderRating = exchange.SenderUser.ExchangeRating }); } return(detailedBook); } }
public BookDetail Read(int bookID) { // TODO refactor this conn.Open(); BookDetail book = new BookDetail(); try { using (SQLiteCommand fmd = conn.CreateCommand()) { fmd.CommandText = @"select * from books where Display = 1 and ID = :bookID ORDER BY ID DESC;"; fmd.CommandType = CommandType.Text; fmd.Parameters.AddWithValue("bookID", bookID); SQLiteDataReader records = fmd.ExecuteReader(); while (records.Read()) { book = MapSQLToObject(records); } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { conn.Close(); } return(book); }
public int Add(BookDetail book) { int id; conn.Open(); SQLiteCommand createQuery = conn.CreateCommand(); using (var localTransaction = conn.BeginTransaction()) { try { //TODO Paramatarise this as in update() string command = "INSERT INTO Books(BookTitle, Author, ISBN, DateStarted, DateCompleted, Score, GoodreadsID," + "YearOfPublication, AmountOfGRReviews, GRScore, ImageURL, Completed, NumberOfPages, Genre, Display)" + "VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}')"; command = FormatCommand(book, command); createQuery.CommandText = command; createQuery.ExecuteNonQuery(); localTransaction.Commit(); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); localTransaction.Rollback(); } finally { id = (int)conn.LastInsertRowId; conn.Close(); } } return(id); }
public IList <Book> Recommend(Preference preference, int limit) { IList <Book> books = new List <Book>(limit); DataLoaderFactory dataLoaderFactory = DataLoaderFactory.getInstance(); IDataLoader loader = dataLoaderFactory.GetLoader(); IRecommender recommender = new PearsonRecommender(); IRatingsAggregator aggregator = new RatingsAggregator(); BookDetail bookDetail = loader.Load(); Dictionary <string, List <int> > bookRatings = aggregator.Aggregate(bookDetail, preference); List <int> Base = bookRatings[preference.ISBN]; bookRatings.Remove(preference.ISBN); Dictionary <string, double> coefficients = new Dictionary <string, double>(); foreach (var item in bookRatings) { coefficients.Add(item.Key, recommender.GetCorrelation(Base, bookRatings[item.Key])); } coefficients = coefficients.OrderByDescending(x => x.Value).ToDictionary(a => a.Key, b => b.Value); coefficients = coefficients.Take(limit).ToDictionary(a => a.Key, b => b.Value); books.Add(bookDetail.Books.Find(b => b.ISBN == preference.ISBN)); foreach (var isbn in coefficients.Keys) { books.Add(bookDetail.Books.Find(b => b.ISBN == isbn)); } return(books); }
[ActionName("Create")] //Exclude Property public ActionResult Createbook([Bind(Exclude = "bookName")] BookDetail bookDetail) { //TryUpdateModel(bookDetail); books.AddBook(bookDetail); TempData["Message"] = "Books added"; return(RedirectToAction("Index")); }
public void UpdateBook(BookDetail bookDetail) { BookDetail bookDetails = GetBookById(bookDetail.bookId); bookDetails.bookName = bookDetail.bookName; bookDetails.bookAuthor = bookDetail.bookAuthor; }
public ActionResult BulkSelectNewBook(HttpPostedFileBase books) { string path = UploadFile(books); List <BookDetail> bookSelection = new List <BookDetail>(); IEnumerable <string> lines = System.IO.File.ReadLines(path); List <string> keys = new List <string>(); for (int idx = 0; idx < lines.Count(); idx++) { if (idx == 0) { keys = lines.ElementAt(idx).Split(',').ToList <string>(); continue; } else { var dict = keys.Zip(lines.ElementAt(idx).Split(',').ToList <string>(), (k, v) => new { k, v }) .ToDictionary(x => x.k, x => x.v); var goodreadsResp = QueryGoodReadsAPI(dict["Title"]); BookDetail book = goodreadsResp[0]; book.DateStarted = DateTime.Parse(dict["Started"]); book.DateCompleted = (string.IsNullOrEmpty(dict["Finished"]) ? (DateTime?)null : DateTime.Parse(dict["Finished"])); book.Completed = (!string.IsNullOrEmpty(dict["Finished"]) ? true : false); book.Score = (!string.IsNullOrEmpty(dict["Finished"]) ? float.Parse(dict["Score"]) : (float?)null); _DatabaseController.Insert(book); bookSelection.Add(book); } } return(View("BulkSelectBook", bookSelection)); }
public ActionResult Details(string name) { BookDetail book = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44371/api/"); string token = DeserializeToken(); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //var responseTask = client.PostAsJsonAsync("Book?Id=" + id.ToString(), id); var responseTask = client.GetAsync("Book?Name=" + name); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <BookDetail>(); readTask.Wait(); book = readTask.Result; } } return(View(book)); }
/// <summary> /// Detail of the book. /// </summary> /// <param name="id">DId of the book</param> /// <returns>Page with the main detail page</returns> async public Task <IActionResult> Detail(int id) { string userId = null; if (User.Identity.IsAuthenticated) { userId = (await _userManager.GetUserAsync(HttpContext.User)).Id; } var bookDetail = new BookDetail(id, userId); if (bookDetail.Book == null) { return(View("Error")); } if (User.Identity.IsAuthenticated) { var db = new BookRecommenderContext(); var user = db.Users.Where(u => u.Id == userId)?.FirstOrDefault(); if (user == null) { return(View("Error")); } var ua = new UserActivity(user, ActivityType.BookDetailViewed, id.ToString()); await db.UsersActivities.AddAsync(ua); await db.SaveChangesAsync(); } return(View(bookDetail)); }
private List <BookDetail> QueryGoodReadsAPI(string title) { if (!string.IsNullOrEmpty(title)) { title = title.Trim().Replace(' ', '+').Replace("\'", ""); } string url; url = "https://www.goodreads.com/search/index.xml?key=" + _Key + "&q=" + title; //dynamic res; //XDocument doc = new XDocument(); XDocument doc = XDocument.Load(url); List <BookDetail> results = new List <BookDetail>(); foreach (var result in doc.Descendants("work")) { BookDetail book = CleanXMLSearchResponse(result); book.Display = true; GetAdditionalInformationXML(book); book.GRScore = Math.Round(book.GRScore, 2); results.Add(book); } return(results); }
public ActionResult Create(BookDetail bookDetail) { if (Session["UserEmail"] != null) { string fileName = Path.GetFileName(bookDetail.ImageFile.FileName); bookDetail.Url = "~/BooksImages/" + fileName; fileName = Path.Combine(Server.MapPath("~/BooksImages/"), fileName); bookDetail.ImageFile.SaveAs(fileName); ModelState.Clear(); if (ModelState.IsValid) { db.BookDetails.Add(bookDetail); db.SaveChanges(); return(RedirectToAction("Books")); } ViewBag.Author_Id = new SelectList(db.AuthorDetails, "Author_Id", "Name", bookDetail.Author_Id); return(View(bookDetail)); } else { Response.Write("<script>alert('Please Login')</script>"); Session.Clear(); return(RedirectToAction("SignIn", "Authentication")); } }
private void listViewBooks_DoubleClick(object sender, EventArgs e) { int lineNumber = this.listView_Books.SelectedIndices[0]; var line = this.listView_Books.Items[lineNumber]; string bid = line.SubItems[0].Text; int id = int.Parse(bid); BookDetail book; if (!BookList.tryFind(id, out book)) { return; } Form_Item item = new Form_Item(book); item.ReturnBook += (o, e1) => { BookDetail tmp = item.book; tmp.BookInfo.buildRawData(); tmp.BookPrint.buildRawData(); // 填充到 BookList BookList.ReplaceTo(id, tmp); BookDetail now; BookList.tryFind(id, out now); // 重新整理内容到 ListView RefreshBookList(ref now, ref line); }; item.ShowDialog(); }
public async Task <IActionResult> PutBookDetail(int id, BookDetail bookDetail) { if (id != bookDetail.BookId) { return(BadRequest()); } _context.Entry(bookDetail).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BookDetailExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult Edit(int id) { BookRepositry bookRepositry = new BookRepositry(); BookDetail book = bookRepositry.GetBookById(id); return(View(book)); }
public BookDetail getBookInfo(int id) { BookDetail book = new BookDetail(); book = db.BookDetails.FirstOrDefault(x => x.Id == id); return(book); }
public int AddDetail(BookDetail obj) { db.BookDetail.Add(obj); db.SaveChanges(); return((int)obj.StudentId); }
public Response Insert(BookDetail data) { string message = "Failed"; bool result = false; Response res = new Response(); try { if (data.ID == Guid.Empty) { data.ID = Guid.NewGuid(); db.BookDetail.Add(data); db.SaveChanges(); message = "Save data success"; result = true; } res.ID = data.ID; res.Message = message; res.Result = result; return(res); } catch (Exception ex) { res.Message = ex.Message; res.Result = false; return(res); } }
public static async Task GetBookQuasiDetail(BookDetail book) { var query = new QueryObject("GetBookQuasiDetail") { BookId = book.ID }; if (Storage.Test) { book.BookCover = new Windows.UI.Xaml.Media.Imaging.BitmapImage( new Uri("https://gss0.baidu.com/7LsWdDW5_xN3otqbppnN2DJv/doc/pic/item/6159252dd42a283478df074e58b5c9ea15cebf7d.jpg")); book.BookFullName = RandomName(); book.BookName = book.BookFullName.CutString(); book.AuthorName = "松浦彌太郎"; book.Labels = "生活 - 随笔"; book.Price = 28; book.Discount = 95; book.OverallRating = 4.5; return; } var recv = await Connection.SendAndReceive.GlobalLock(query); book.BookCover = new Windows.UI.Xaml.Media.Imaging.BitmapImage( new Uri(recv.BookCoverUrl)); book.BookFullName = recv.BookName; book.BookName = book.BookFullName.CutString(); book.AuthorName = recv.AuthorName; book.Labels = recv.MainAndSubLabel; book.Price = recv.Price.Value; book.Discount = recv.Discount.Value; book.OverallRating = recv.OverallRating.Value; }
public IHttpActionResult GetBookByTitle(string title) { BookService service = CreateBookService(); BookDetail book = service.GetBookByTitle(title); return(Ok(book)); }
public IHttpActionResult GetBookById(int id) { BookService service = CreateBookService(); BookDetail book = service.GetBookById(id); return(Ok(book)); }
// GET: BookDetails/Details/5 public ActionResult Details(int?id) { if (Session["UserName"] != null) { if (Session["UserName"].ToString() == "kunj") { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookDetail bookDetail = db.BookDetails.Find(id); if (bookDetail == null) { return(HttpNotFound()); } return(View(bookDetail)); } else { Session["Message"] = "You are not Authorize"; return(RedirectToAction("Login", "UserDetails")); } } else { Session["Message"] = "You are Not Login"; return(RedirectToAction("Login", "UserDetails")); } }
public ActionResult Addnew(BookDetail book) { try { // TODO: Add insert logic here dbmodel.BookDetails.Add(book); dbmodel.SaveChanges(); return(RedirectToAction("Index")); } //else //{ // // ViewBag.Error = TempData["Year should be between 1500 and " + Convert.ToInt32(book.Year)]; // // TempData["error"]="Year should be between 1500 and " + Convert.ToInt32(book.Year); // // Response.Write("Year should be between 1500 and " + Convert.ToInt32(book.Year)); // //("Year should be between 1500 and " + Convert.ToInt32(book.Year)); // return RedirectToAction("Index"); //} // } catch { return(View()); } }
public Form_Item(int bid = 1) { InitializeComponent(); __BookID = bid; book = null; isNewComer = true; OnDisplay(); }
public Form_Item(BookDetail reff) { InitializeComponent(); __BookID = reff.BookID; book = reff; isNewComer = false; OnDisplay(); }
public ActionResult DeleteConfirmed(int id) { BookDetail bookDetail = db.BookDetails.Find(id); db.BookDetails.Remove(bookDetail); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Delete(BookDetail book) { book.Display = false; _DatabaseController.Update(book); return(View("Details", new List <BookDetail> { book })); }
private void buttonUpdate_Click(object sender, EventArgs e) { if (book == null) { book = new BookDetail(); book.BookID = __BookID; } if (this.textBoxName.Text == "") { MessageBox.Show("教材名称信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookInfo.Name = this.textBoxName.Text; if (this.textBoxAuthor.Text == "") { MessageBox.Show("作者信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookInfo.Author = this.textBoxAuthor.Text; if (this.comboBoxTitle.SelectedIndex == -1) { MessageBox.Show("作者职称信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookInfo.AuthorTitle = (_BookInformation.AcademicTitle)this.comboBoxTitle.SelectedIndex; if (this.textBoxPublish.Text == "") { MessageBox.Show("出版社信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookInfo.PublishingCompany = this.textBoxPublish.Text; if (this.comboBoxBelong.SelectedIndex == -1) { MessageBox.Show("教材类别信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookInfo.Belonging = (_BookInformation.Category)this.comboBoxBelong.SelectedIndex; if (this.radioButtonMono.Checked) book.BookInfo.Attr = _BookInformation.Property.Monograph; else book.BookInfo.Attr = _BookInformation.Property.Textbook; if (this.numericUpDownWords.Value <= 0) { MessageBox.Show("教材字数信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookPrint.WordCount = (int)this.numericUpDownWords.Value; if (this.radioButtonBindPaper.Checked) book.BookPrint.BookBinding = _BookPrinting.Binding.Paperback; else book.BookPrint.BookBinding = _BookPrinting.Binding.Hardback; if (this.radioButtonSizeA4.Checked) book.BookPrint.BookSize = _BookPrinting.BookSizeFormat.A4Paper; else book.BookPrint.BookSize = _BookPrinting.BookSizeFormat.A5Paper; if (this.comboBoxBookCnt.SelectedIndex == -1) { MessageBox.Show("教材册数信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookPrint.BookCount = (_BookPrinting.BookNumer)(1 + this.comboBoxBookCnt.SelectedIndex); if (this.comboBoxPaper.SelectedIndex == -1) { MessageBox.Show("正文用纸信息为空!", "输入错误", MessageBoxButtons.OK); return; } book.BookPrint.PaperUsing = (_BookPrinting.PaperFormat)this.comboBoxPaper.SelectedIndex; book.BookPrint.IsColorful = this.radioButtonAye.Checked; this.Text = "*[未更新到数据库] " + this.labelBookID.Text + book.BookInfo.Name; this.button_OK.Enabled = true; this.button_Update.Enabled = false; }
private void TryOpenExcel(string name) { ExcelOperator excel = new ExcelOperator(); excel.OpenExcel(name); int idxRow = 2; while (true) { Range test = excel[idxRow, 1]; if (test.Value2 == null) break; else idxRow++; } int cnt = idxRow; Form_ImportProgress fip = new Form_ImportProgress(cnt - 2); fip.Show(); for (idxRow = 2; idxRow < cnt; idxRow++ ) { Range range = excel[idxRow, 1]; string[] raw1 = new string[6]; for (int idxColumn = 1; idxColumn <= 6; idxColumn++) { Range cell = excel[idxRow, idxColumn]; raw1[idxColumn - 1] = cell.Value2; } if (BookList.isExist(raw1[0], raw1[1], raw1[3])) continue; string[] raw2 = new string[6]; int word = (int)Math.Round(excel[idxRow, 7].Value2); raw2[0] = word.ToString(); for (int idxColumn = 8; idxColumn <= 12; idxColumn++) { Range cell = excel[idxRow, idxColumn]; raw2[idxColumn - 7] = (string)cell.Value2; } BookDetail item = new BookDetail(0, raw1, raw2); BookList.Add(BookList.getNextBID(), item); // ProgressBar fip.ChangeTo(idxRow - 1); } excel.QuitExcel(); fip.Close(); }
private void RefreshBookList(ref BookDetail now, ref ListViewItem line) { for (int i = 0; i < 6; i++) { line.SubItems[1 + i].Text = now.BookInfo._rawData_[i]; } for (int i = 0; i < 6; i++) { line.SubItems[7 + i].Text = now.BookPrint._rawData_[i]; } }
private void tSMI_Sendto_Click(object sender, EventArgs e) { List<BookInformation> data = new List<BookInformation>(); for (int i = 0, sz = listView_Books.SelectedItems.Count; i < sz; i++) { string id = listView_Books.SelectedItems[i].SubItems[0].Text; BookDetail tmp = new BookDetail(); BookList.tryFind(int.Parse(id), out tmp); data.Add(tmp.GetBookInfo()); } Form_SendTo work = new Form_SendTo(data, onlineUsers); work.ShowDialog(); }
/// <summary> /// 标准构造函数 /// </summary> /// <param name="info">教材属性</param> /// <param name="value">教材评价</param> public BookFinal(BookDetail info, BookEvaluaion value) { MainInfo = info; MainValue = value; }
private void FindBookInfo(int bid, out BookDetail info) { BookList.tryFind(bid, out info); }