private static void MergeValues(BookModel bookModel, BookDTO bookDTO)
        {
            bookModel.Author = bookDTO.Author;
            bookModel.Name = bookDTO.Name;

            bookModel.Image = GetImageSource(bookDTO.Image);
        }
 public static void UpdateFrom(this ObservableCollection<BookModel> collection, IEnumerable<BookDTO> mergeSource)
 {
     Execute.OnUIThreadAsync(() =>{
         foreach(var bookDTO in mergeSource)
         {
             var bookModel = collection.FirstOrDefault(model => model.Id == bookDTO.Id);
             if(bookModel == null)
             {
                 bookModel = new BookModel
                 {
                     Id = bookDTO.Id
                 };
                 collection.Add(bookModel);
             }
             MergeValues(bookModel, bookDTO);
         }
         var toRemove = collection.Where(orig => mergeSource.Any(merged => merged.Id == orig.Id) == false).ToArray();
         foreach(var model in toRemove)
         {
             collection.Remove(model);
         }
     });
 }
Exemple #3
0
        public async Task <IActionResult> AddNewBook(BookModel book)
        {
            if (book.CoverImage != null)
            {
                string folder           = "imgs/userUploadImages";
                string serverRootPath   = _webHostEnvironment.WebRootPath;
                string fileName         = Guid.NewGuid().ToString() + "_" + book.CoverImage.FileName;
                string serverFolderPath = Path.Combine(serverRootPath, folder, fileName);

                await book.CoverImage.CopyToAsync(new FileStream(serverFolderPath, FileMode.Create));

                //这是供前端使用的URL地址,在HTML中需要在图片地址前加上"/"
                book.CoverImageUrl = "/" + Path.Combine(folder, fileName);
            }
            if (book.BookPdf != null)
            {
                string folder           = "pdfs";
                string serverRootPath   = _webHostEnvironment.WebRootPath;
                string fileName         = Guid.NewGuid().ToString() + "_" + book.BookPdf.FileName;
                string serverFolderPath = Path.Combine(serverRootPath, folder, fileName);

                await book.BookPdf.CopyToAsync(new FileStream(serverFolderPath, FileMode.Create));

                book.BookPdfUrl = "/" + Path.Combine(folder, fileName);
            }
            int id = _bookRepository.CreateABook(book);

            if (id > 0)
            {
                return(RedirectToAction(nameof(AddNewBook), new { isSuccess = true, bookId = id }));
            }
            return(View());

            //直接重定向到被创建的书记页面
            //return RedirectToAction("BookDetail", new { id });
        }
Exemple #4
0
        public IHttpActionResult Post(BookModel book)
        {
            try
            {
                BookService bookService = new BookService();
                Book        dbBook      = new Book();

                //dbBook.Description = book.Description;
                //dbBook.Author = book.Author;
                //dbBook.Genre = book.Genre;
                //dbBook.Quantity = book.Quantity;
                //dbBook.Title = book.Title;
                book.CopyValuesToEntity(dbBook);
                bookService.AddBook(dbBook);

                // return the newly created Book
                BookModel newBook = new BookModel(dbBook);
                return(Ok(newBook));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #5
0
        public IActionResult Post([FromBody] BookModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var authors = model.Authors.Select(it => new Author(it.Name, it.LastName, it.Id)).ToArray();
                var result  = bookService.AddBook(model.ISBN, model.Title, model.Sypnosis, model.NumberPages, new Editorial(model.Editorial.Name, model.Editorial.Campus, model.Editorial.Id), authors);

                if (!result)
                {
                    return(StatusCode(500, "Book was not create"));
                }

                return(Ok());
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
    //métodos CRUD - ler um dado no banco
    public List <BookModel> Search(int id)
    {
        //abrindo o canal com o banco e fazendo a busca
        NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5434;User Id=postgres;Password=admin;Database=challange;");
        NpgsqlCommand    cmd  = new NpgsqlCommand();

        cmd.Connection  = conn;
        cmd.CommandText = "SELECT * FROM BOOK WHERE ID='" + id + "';";
        cmd.CommandType = CommandType.Text;

        conn.Open();

        List <BookModel> book = new List <BookModel>(id);

        try
        {
            NpgsqlDataReader data = cmd.ExecuteReader();
            while (data.Read())
            {
                BookModel book1 = new BookModel();
                book1.Id              = (int)data["id"];
                book1.Title           = (string)data["title"];
                book1.Author          = (string)data["author"];
                book1.Release         = (int)data["release"];
                book1.PublishingHouse = (string)data["publishing"];
                book1.Category        = (string)data["category"];
                book1.Description     = (string)data["description"];
                book.Add(book1);
            }
        }
        finally
        {
            conn.Close();
        }
        return(book);
    }
Exemple #7
0
        private async void UpdateBook()
        {
            ErrorMsgVisibility = Visibility.Collapsed;
            if (SelectedBook == null || !CheckAllInputFields())
            {
                ErrorMsg           = Properties.Resources.SelectBookErrorMsg;
                ErrorMsgVisibility = Visibility.Visible;
                return;
            }

            var _searchedBook = BookCollection.FirstOrDefault(s => s.AuthorName == AuthorName);

            // Check if there is already a book with same name and same authorname

            if (_searchedBook != null && _searchedBook.BookName == BookName && Convert.ToInt32(Quantity) == _searchedBook.Quantity)
            {
                ErrorMsg           = Properties.Resources.SameBookExistMsg;
                ErrorMsgVisibility = Visibility.Visible;
                return;
            }

            BookModel book = new BookModel()
            {
                BookId     = SelectedBook.BookId,
                BookName   = this.BookName,
                AuthorName = this.AuthorName,
                Quantity   = Convert.ToInt32(this.Quantity)
            };

            _log.Message("Updating Book");
            await _dataAccess.UpdateData(book, Properties.Resources.UpdateBook);

            GetBooks();
            InvokeBookUpdate();
            ClearAllField();
        }
        public ActionResult EditBook(BookModel model)
        {
            if (model != null)
            {
                if (ModelState.IsValid)
                {
                    var  mapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap <BookModel, Book>()));
                    Book book   = mapper.Map <BookModel, Book>(model); //From-to

                    if (model.Id > 0)
                    {
                        this.materialService.UpdateMaterial(book);
                    }
                    else
                    {
                        this.materialService.AddMaterial(book);
                    }

                    return(RedirectToAction("AdminPanelMaterial"));
                }
                return(View(model));
            }
            return(View());
        }
Exemple #9
0
        }         //加载到datagridview中

        public void AddBookInfo(BookModel _bookmodel)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load("Book.xml");
            XmlNode root = doc.SelectSingleNode("bookstore");

            XmlElement xelKey = doc.CreateElement("book");

            XmlAttribute a = doc.CreateAttribute("课程类型");

            a.InnerText = _bookmodel.BookType;
            xelKey.SetAttributeNode(a);

            XmlAttribute b = doc.CreateAttribute("编号");

            b.InnerText = Convert.ToString(_bookmodel.BookID);
            xelKey.SetAttributeNode(b);

            XmlElement c = doc.CreateElement("书名");

            c.InnerText = _bookmodel.BookName;
            xelKey.AppendChild(c);

            XmlElement d = doc.CreateElement("作者");

            d.InnerText = _bookmodel.BookAuthor;
            xelKey.AppendChild(d);

            XmlElement e = doc.CreateElement("价格");

            e.InnerText = _bookmodel.BookPrice;
            xelKey.AppendChild(e);
            root.AppendChild(xelKey);
            doc.Save("Book.xml");
        }  //增加
Exemple #10
0
 public void AddBook(BookModel book)
 {
     Books.Add(book);
 }
Exemple #11
0
 public static bool Save(BookModel book)
 {
     return(BookDAL.Save(new BookDTO(book)));
 }
Exemple #12
0
 public static Book ConvertToBookEntity(this BookModel bookModel) =>
 new Book(0, bookModel.Title, bookModel.Description, bookModel.Author, bookModel.Interpreter, bookModel.Language,
          bookModel.Launch, bookModel.Price);
        /// <summary>
        /// Returns a list of all books in the database
        /// </summary>
        /// <returns></returns>
        public static List <BookModel> GetAllBooks()
        {
            var books = new List <BookModel>();

            //BookModel, authorId, genreId
            var authorAndGenreIds = new List <Tuple <BookModel, int, int> >();

            var connString = ConfigurationManager.ConnectionStrings["Biblioteka.Properties.Settings.BibliotekaDBConnectionString"].ToString();
            var connection = new SqlConnection(connString);

            connection.Open();

            var command = new SqlCommand($"SELECT * FROM Książki", connection);

            using (var reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var book = new BookModel()
                        {
                            Id    = reader.GetInt32(0),
                            Tytuł = reader.GetString(3).Trim()
                        };
                        var authorId = reader.GetInt32(1);

                        var genreId = reader.GetInt32(2);

                        authorAndGenreIds.Add(new Tuple <BookModel, int, int>(book, authorId, genreId));
                    }
                }
            }

            foreach (var elem in authorAndGenreIds)
            {
                AuthorModel author         = null;
                var         getAuthorModel = new SqlCommand($"SELECT * FROM Autorzy WHERE Id={elem.Item2}", connection);
                using (var authorReader = getAuthorModel.ExecuteReader())
                {
                    if (authorReader.HasRows)
                    {
                        authorReader.Read();
                        author = new AuthorModel()
                        {
                            Id            = elem.Item2,
                            Imię          = authorReader.GetString(1).Trim(),
                            Nazwisko      = authorReader.GetString(2).Trim(),
                            DataUrodzenia = authorReader.GetDateTime(3),
                            Biografia     = authorReader.GetString(4).Trim()
                        };
                    }
                }


                GenreModel genre         = null;
                var        getGenreModel = new SqlCommand($"SELECT * FROM Gatunki WHERE Id={elem.Item3}", connection);
                using (var genreReader = getGenreModel.ExecuteReader())
                {
                    if (genreReader.HasRows)
                    {
                        genreReader.Read();
                        genre = new GenreModel()
                        {
                            Id    = elem.Item3,
                            Nazwa = genreReader.GetString(1).Trim()
                        };
                    }
                }

                elem.Item1.Autor = author;

                elem.Item1.Gatunek = genre;

                books.Add(elem.Item1);
            }

            connection.Close();

            return(books);
        }
Exemple #14
0
        public ActionResult Book(BookModel model, register reg)
        {
            List <Addasset> assetlist = db.addasset.ToList();

            ViewBag.list = new SelectList(assetlist, "asset", "asset");
            string date  = Request["date"];
            string asset = Request["asset"];

            TimeSpan itime = TimeSpan.Parse(Request["intime"]);
            TimeSpan otime = TimeSpan.Parse(Request["outtime"]);
            var      items = db.bookm.Where(x => x.date == date && x.intime >= itime && x.outtime <= otime && x.asset == asset).SingleOrDefault();

            if (items == null)
            {
                var regs = db.regmodel.Where(x => x.phone.Equals(reg.check) && x.pin.Equals(reg.pin) || x.email.Equals(reg.check) && x.pin.Equals(reg.pin)).SingleOrDefault();
                if (regs != null)
                {
                    var email = (from a in db.regmodel
                                 where a.phone.Equals(reg.check) || a.email.Equals(reg.check)
                                 select new
                    {
                        a.email,
                        a.name,
                        a.phone
                    }).SingleOrDefault();
                    string Email = email.email;

                    model.name  = email.name;
                    model.phone = email.phone;
                    model.email = email.email;
                    db.bookm.Add(model);

                    model.status = "pending";
                    db.bookm.Add(model);
                    db.SaveChanges();



                    try
                    {
                        var sendmail = new MailAddress("enter your valid email address", "Akhil");
                        var receiver = new MailAddress(Email, "Buddy");
                        var password = "";    //enter your email password
                        var subject  = "Request for Asset!!";
                        var body     = "This is regarding the request by " + model.name + " for the " + model.asset + "on " + date + "from" + itime + "to" + otime;



                        var smptp = new SmtpClient
                        {
                            Host                  = "smtp.gmail.com",
                            Port                  = 587,
                            EnableSsl             = true,
                            DeliveryMethod        = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials           = new NetworkCredential(sendmail.Address, password)
                        };
                        using (var mess = new MailMessage(sendmail, receiver)
                        {
                            Subject = subject,
                            Body = body,
                        })
                        {
                            smptp.Send(mess);
                        }
                        TempData["status"] = "Please keep on checking your mail.Booking is Confirmed for  " + date + " and " + itime + " and " + otime + "";

                        return(RedirectToAction("Index"));
                    }
                    catch
                    {
                        TempData["probblem"] = "Problem while sending email, Please check details.";
                    }
                }
                else
                {
                    ViewBag.notauser = "******";
                    RedirectToAction("Book");
                }
            }
            else
            {
                BookinView bv = new BookinView
                {
                    book = db.bookm.Where(x => x.date == date && x.intime >= itime && x.outtime <= otime).ToList()
                };
                return(View(bv));
            }



            return(View());
        }
Exemple #15
0
        public ActionResult Delete(int id, BookModel model)
        {
            GetService <BookService>().Delete(id);

            return(RedirectToAction("Index"));
        }
Exemple #16
0
 public WordCounter(BookModel bookModel)
 {
     _bookModel = bookModel;
 }
Exemple #17
0
 public string AddBook(BookModel bookObj)
 {
     return(_bookObj.AddBook(bookObj));
 }
Exemple #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BookModel"/> class.
 /// Copy constructor.
 /// </summary>
 public BookModel(BookModel bookModel)
     : base(bookModel)
 {
     this.Author = bookModel.Author;
 }
 private void OpenBookView()
 {
     CurrentBook = new BookModel();
     BV          = new BookView();
     BV.Show();
 }
        public HttpResponseMessage ModifyBook(BookModel model, string key)
        {
            try
            {
                var context = new LibrarySystemContext();
                using (context)
                {
                    var book = context.Books.FirstOrDefault(b => b.Key == key);
                    if (book == null)
                    {
                        throw new ArgumentException("Няма книга с такъв уникален номер!");
                    }

                    var author = context.Authors.FirstOrDefault(a => a.Name == model.AuthorName);
                    if (author == null)
                    {
                        context.Authors.Add(new Author()
                        {
                            Name = model.AuthorName
                        });
                        context.SaveChanges();
                    }

                    book.Title = model.Title;
                    book.Key = model.Key;
                    book.Author = author;
                    book.Year = model.Year;
                    book.Description = model.Description;

                    context.SaveChanges();
                }

                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.NotModified,
                                          ex.Message);
                return response;
            }
        }
Exemple #21
0
        private void FindFiles(FormCollection formCollection, HttpFileCollectionBase files, ref HttpPostedFileBase fileBook, ref HttpPostedFileBase fileImg, BookModel bookModel, Controller controller)
        {
            foreach (string item in files)
            {
                HttpPostedFileBase file = files[item];

                if (file.ContentLength > 0)
                {
                    string extension = Path.GetExtension(file.FileName);

                    string path = string.Empty;

                    if (extension.ToLower() != ".pdf")
                    {
                        path               = "../imgs/" + bookModel.BookId.ToString() + extension;
                        fileImg            = file;
                        bookModel.UrlImage = path;
                    }
                    else
                    {
                        path              = "../Files/" + bookModel.BookId.ToString() + extension;
                        fileBook          = file;
                        bookModel.UrlBook = path;
                        this.RemoveFromModelState(controller.ModelState, "UrlBook");
                    }
                }
            }
        }
        public AllBooksViewModel()
        {
            _bookModel = new BookModel();

            InitializeCommands();
        }
Exemple #23
0
        private void addBookButton_Click(object sender, EventArgs e)
        {
            #region Check for maximum
            if (borrowFlowLayout.Controls.Count > SettingsModel.MaxBookCount)
            {
                MessageBox.Show("Can't lend more books", "Maximum Reached");
                return;
            }
            #endregion

            string accessNo = addBookNoTextBox.Text;

            #region Check whether exists
            bool isExists = BookController.IsBookExists(accessNo);
            if (!isExists)
            {
                ValidationClass.ShowInvalidError(
                    highlighter,
                    addBookNoTextBox,
                    "There is not a Book with this Accession Number.",
                    "Invalid Accession No"
                    );
                return; //End Execution
            }
            #endregion

            #region Is Book Available (No member has borrowed)
            bool isAvailable = TransactionController.GetMember_NotReturned(accessNo) == null;

            if (!isAvailable)
            {
                ValidationClass.ShowInvalidError(
                    highlighter,
                    addBookNoTextBox,
                    "The Book has been borrowed by other Member.\n" +
                    "The Book is not available now.",
                    "Not Available"
                    );
                return; //End Execution
            }
            #endregion

            #region Check for Already Exists
            foreach (Control control in borrowFlowLayout.Controls)
            {
                BorrowBookPanel bookPanel = (BorrowBookPanel)control;
                if (bookPanel.Book.AccessNo == accessNo)
                {
                    ValidationClass.ShowInvalidError(
                        highlighter,
                        addBookNoTextBox,
                        "The Book has been already added.",
                        "Duplicating Book"
                        );
                    return;
                }
            }
            #endregion

            BookModel       book            = BookController.GetBook(accessNo);
            BorrowBookPanel borrowBookPanel = new BorrowBookPanel();
            borrowBookPanel.Book           = book;
            borrowBookPanel.ParentTabPanel = this;
            borrowFlowLayout.Controls.Add(borrowBookPanel);
            returnBorrowFlowLayout_Resize(borrowFlowLayout, null);

            addBookNoTextBox.Text = "";
            addBookNoTextBox.Select();
        }
Exemple #24
0
 public Book(BookModel bookModel, IMonitorLogger logger, IFileIO fileIO)
 {
     Model   = bookModel;
     _logger = logger;
     _fileIO = fileIO;
 }
        public List <BookModel> AllBooks()
        {
            var bookModel = new BookModel();

            return(bookModel.Books.ToList());
        }
Exemple #26
0
 public BookNodeViewModel(BookModel book, LibraryNodeViewModel nodeLibrary)
     : base(nodeLibrary, book.Name, book, false)
 {
     Book = book;
 }
Exemple #27
0
        public JsonResult Register(BookModel val)
        {
            string       JsfunctionName = "CalculateReturn";  // dönüşte çalıştırılacak funciton adı parametresi
            OptinalClass _OptinalClass  = new OptinalClass(); // genel kullanım class yapım
            OptinalClass rtrn           = new OptinalClass(); // genel kullanım class yapım
            BookService  _BookService   = new BookService();

            if (Convert.ToDateTime(val.BeginDate) > Convert.ToDateTime(val.EndDate))// false ise return dön
            {
                rtrn.OptinalClass_val = false;
                rtrn.OptinalClass_msg = "Başlangıç Tarihi, Bitiş Tarihinden Büyük Olamaz!";
                return(Json(new { value = true, jqueryFunc = ("" + JsfunctionName + "({'value':'" + rtrn.OptinalClass_val + "','Return':'" + rtrn.OptinalClass_msg + "'})").Replace('\'', '"') })); // code blok burada return döndürsün
            }
            if (val.Country == "0")                                                                                                                                                                 //ülke gelen değer kontrol
            {
                rtrn.OptinalClass_val = false;
                rtrn.OptinalClass_msg = "Ülke Seçiniz!";
                return(Json(new { value = true, jqueryFunc = ("" + JsfunctionName + "({'value':'" + rtrn.OptinalClass_val + "','Return':'" + rtrn.OptinalClass_msg + "'})").Replace('\'', '"') }));// code blok burada return döndürsün
            }
            try
            {
                int.TryParse(val.Country, out int countryID);
                _OptinalClass.OptinalClass_ID = countryID;
                List <WorkDay> _WorkDayList = Tool.AsObjectList <WorkDay>(_BookService.GetWorkDayList(Tool.AsJson(_OptinalClass))); //Service projesinden, db de ülkeye göre tanımlanan çalışma günlerini alıyorum.
                List <Holiday> _Holiday     = _BookService.GetHolidayList(Tool.AsJson(_OptinalClass));                              //Service projesinden, db de ülkeye göre tanımlanan tatil günlerini alıyorum.

                DateTime BeginDate = Convert.ToDateTime(val.BeginDate);
                DateTime EndDate   = Convert.ToDateTime(val.EndDate);

                double TotalDay = (EndDate - BeginDate).TotalDays + 1; //dahil edilen gün sayısı

                int    BookDay    = 0;                                 //çalışma gü sayısı
                int    weekOfDay  = -1;                                // gün, haftanın hangi indexinde(squence)
                bool   isworkDay  = false;                             // çalışma günü mü
                bool   isholiday  = false;                             // tatil günü mü
                float  PenaltyPay = 0;                                 //ceza ücreti
                string Curreny    = "";                                //para birimi
                Curreny = Tool.AsObjectList <Country>(_BookService.GetCountryList()).Where(x => x.ID == countryID).SingleOrDefault().Currency;
                for (int i = 0; i < TotalDay; i++)                     //para birimini alıyorum
                {
                    #region Gün sequnce belirleme
                    weekOfDay = Tool.GetDayOfWeek(BeginDate.AddDays(i));//helper daki tool da, tarih haftanın hangi gününde bilgisini alıyorum.
                    #endregion
                    isworkDay = false;
                    foreach (WorkDay workDay in _WorkDayList) //çalışma günü mü?
                    {
                        if (workDay.DaySequence == weekOfDay) //squence e göre bakıyorum.
                        {
                            isworkDay = true;                 // çalışma günü ise şarta girecek
                            break;
                        }
                    }
                    isholiday = false;
                    foreach (Holiday holiday in _Holiday)// tatile denk geliyor mu?
                    {
                        if (holiday.Date == BeginDate.AddDays(i))
                        {
                            isholiday = true;// tatilse şarta girmicek
                            break;
                        }
                    }
                    if (!isholiday && isworkDay) //tatil değilse ve çalışma günü ise
                    {
                        BookDay++;               // günü 1 arttır.
                    }
                }
                if (BookDay > 10)                                                       // 10 çalışma gününden fazla ise ceza ücretine tabi olacak
                {
                    PenaltyPay = (BookDay - 10) * 5;                                    //hergün 5 para birimi
                }
                rtrn.OptinalClass_msg          = BookDay.ToString();                    // Çalışma gün sayısı
                rtrn.OptinalClass_optional_Msg = PenaltyPay.ToString() + " " + Curreny; // var ise Ceza tutarı
                rtrn.OptinalClass_val          = true;
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);                                                                                                                                                                                          //Elmah kullanarak olası hataları Db ye loglayacağım.
            }
            return(Json(new { value = true, jqueryFunc = ("" + JsfunctionName + "({'value':'" + rtrn.OptinalClass_val + "','WorkDays':'" + rtrn.OptinalClass_msg + "','Penalty':'" + rtrn.OptinalClass_optional_Msg + "'})").Replace('\'', '"') })); // Json dönerken main.js te tanımladığım form submit fonksiyonu çalıştığından geriye gerekli parametreleri tanımlıyorum.
        }
Exemple #28
0
 /// <summary>
 /// Creates a new book
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='book'>
 /// the book object
 /// </param>
 public static object Post(this IBooks operations, BookModel book)
 {
     return(Task.Factory.StartNew(s => ((IBooks)s).PostAsync(book), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Exemple #29
0
        public ActionResult EditBook(int id)
        {
            BookFilterModel filters   = new BookFilterModel();
            FiltersModel    jsonModel = new FiltersModel();
            BookModel       book      = new BookModel();

            using (var client = new HttpClient())
            {
                client.BaseAddress = BaseUrl;

                string url          = "/api/value/getbook?id=" + id.ToString();
                var    responseTask = client.GetAsync(url);
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync <BookModel>();
                    readTask.Wait();

                    book = readTask.Result;
                }
            }
            using (var client = new HttpClient())
            {
                client.BaseAddress = BaseUrl;
                //HTTP GET
                var responseTask = client.GetAsync("/api/value/getfilters");
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync <FiltersModel>();
                    readTask.Wait();

                    jsonModel = readTask.Result;
                }
            }
            if (jsonModel != null)
            {
                filters = new BookFilterModel
                {
                    Authors = jsonModel.Authors.ToList().Select(
                        t => new SelectListItem()
                    {
                        Value    = t.ID,
                        Text     = t.Name,
                        Selected = t.Name == book.AuthorName
                    }
                        ).ToList(),

                    Genres = jsonModel.Genges.ToList().Select(
                        t => new SelectListItem()
                    {
                        Value    = t.ID,
                        Text     = t.Name,
                        Selected = t.Name == book.GenreName
                    }
                        ).ToList(),

                    PublishingHouses = jsonModel.PublishingHouses.ToList().Select(
                        t => new SelectListItem()
                    {
                        Value    = t.ID,
                        Text     = t.Name,
                        Selected = t.Name == book.PublishingHomeName
                    }
                        ).ToList()
                };
            }
            filters.ID           = book.ID.ToString();
            filters.CreationDate = book.Year.ToString();
            filters.Name         = book.Name;
            return(View("EditBook", filters));
        }
Exemple #30
0
 public int InsertBook(BookModel BookEntity)
 {
     return(bookDao.InsertBook(BookEntity));
 }
Exemple #31
0
 public ViewResult AddNewBook(BookModel bookModel)
 {
     return(View());
 }
Exemple #32
0
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCommit_Click(object sender, EventArgs e)
        {
            //输入验证
            //图书类别验证
            if (cboBookTypeOne.SelectedItem == null)
            {
                MessageBox.Show("请选择图书一级类别");
                return;
            }
            if (cboBookTypeTwo.SelectedItem == null)
            {
                MessageBox.Show("请选择图书二级类别");
                return;
            }
            //isban长度必须是纯数字且13位
            if (!ValidateInput.IsInteger(txtBookISBN.Text.Trim()))
            {
                MessageBox.Show("图书的ISBN编号必须是纯数字");
                return;
            }
            if (txtBookISBN.Text.Trim().Length != 13)
            {
                MessageBox.Show("图书的ISBN编号长度必须是13位");
                return;
            }
            //名称和作者不能为空
            if (string.IsNullOrWhiteSpace(txtBookAuthor.Text.Trim()))
            {
                MessageBox.Show("图书作者不能为空");
                return;
            }
            BookModel bkmodel = new BookModel();

            bkmodel.BookId          = txtBookId.Text.Trim();
            bkmodel.BookName        = txtBookName.Text.Trim();
            bkmodel.BookType        = Convert.ToInt32(cboBookTypeTwo.SelectedValue);
            bkmodel.BookAuthor      = txtBookAuthor.Text.Trim();
            bkmodel.BookPrice       = Convert.ToDecimal(txtBookPrice.Text.Trim());
            bkmodel.ISBN            = txtBookISBN.Text.Trim();
            bkmodel.BookPress       = Convert.ToInt32(cboBookPress.SelectedValue);
            bkmodel.BookPublishDate = dtpPublishDate.Value;
            bkmodel.StorageInNum    = Convert.ToInt32(txtStorageInNum.Value);
            bkmodel.StorageInDate   = lblStorageInDate.Value;
            bkmodel.InventoryNum    = Convert.ToInt32(lblInventoryNum.Value);
            bkmodel.BorrowedNum     = Convert.ToInt32(lblBorrowedNum.Value);
            if (pbCurrentImage.Image != null)
            {
                bkmodel.BookImage = SerializeObjectToString.SerializeObject(pbCurrentImage.Image);
            }
            switch (actionflag)
            {
            case 1:
                int result2 = bkbll.InsertBook(bkmodel);
                if (result2 == 1)
                {
                    MessageBox.Show("图书添加成功");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                break;

            case 2:
                int result = bkbll.UpdateBook(bkmodel);
                if (result == 1)
                {
                    MessageBox.Show("图书修改成功");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("图书修改失败");
                    return;
                }
                break;
            }
        }
Exemple #33
0
 public static bool Update(BookModel book)
 {
     return(BookDAL.Update(new BookDTO(book)));
 }
Exemple #34
0
 public BookModel GetBookById(int bookId)
 {
     singleResult = _rep.GetSingle <BookModel, Book.Data.Book>(x => x.BookId == bookId);
     return(singleResult);
 }