Ejemplo n.º 1
0
        public ActionResult addBook_DB()
        {
            string bName   = Request["bookname"];
            string bAuthor = Request["author"];

            if ((bName == "" && bAuthor == "") || (bName != "" && bAuthor == "") || (bName == "" && bAuthor != ""))
            {
                return(RedirectToAction("addBook"));
            }
            else
            {
                book b = new book();
                b.bookName     = bName;
                b.bookAuthor   = bAuthor;
                b.bookEdition  = Request["edition"];
                b.bookCategory = Request["bookCategory"];

                dc.books.InsertOnSubmit(b);
                dc.SubmitChanges();
                return(RedirectToAction("displayAllBooks"));
            }
        }
Ejemplo n.º 2
0
        public List <book> getAll(int size, int page)
        {
            try
            {
                String query = "SELECT book.id, name, shortdes,description,language,image,published,uppoint,downpoint,account.userName,account.displayName\n"
                               + "       FROM [book] inner join account account on book.createby=account.userName ORDER BY (uppoint-downpoint) desc \n"
                               + " OFFSET (" + page + "*" + size + "-" + size + ") ROWS FETCH NEXT " + size + " ROWS ONLY";
                string    query2    = "SELECT book.id, name, shortdes,description,language,image,published,uppoint,downpoint,account.userName,account.displayName FROM [book] inner join account account on book.createby = account.userName ORDER BY (uppoint-downpoint) desc OFFSET (" + page + "*" + size + "-" + size + ") ROWS FETCH NEXT " + size + " ROWS ONLY";
                DataTable dataTable = dataProvider.excuteQuery(query2);

                List <book> list = new List <book>();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    account a = new account();
                    a.username = dataTable.Rows[i]["userName"].ToString();
                    a.fullname = dataTable.Rows[i]["displayName"].ToString();
                    book S = new book();
                    S.id           = int.Parse(dataTable.Rows[i]["id"].ToString());
                    S.shortDes     = dataTable.Rows[i]["shortdes"].ToString();
                    S.name         = dataTable.Rows[i]["name"].ToString();
                    S.des          = dataTable.Rows[i]["description"].ToString();
                    S.language     = dataTable.Rows[i]["language"].ToString();
                    S.img          = dataTable.Rows[i]["image"].ToString();
                    S.upPoint      = Int32.Parse(dataTable.Rows[i]["uppoint"].ToString());
                    S.downPoint    = Int32.Parse(dataTable.Rows[i]["downpoint"].ToString());
                    S.createdby    = a;
                    S.pulishedDate = DateTime.Parse(dataTable.Rows[i]["published"].ToString());
                    list.Add(S);
                }

                return(list);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Paging" + ex.Message);
            }

            return(null);
        }
Ejemplo n.º 3
0
        public ActionResult AddBooks(book book)
        {
            var any = db.books.SingleOrDefault(c => c.title == book.title && c.pub_date == book.pub_date && c.publisher == book.publisher);

            if (any != null)
            {
                ViewBag.ExistanceError = "This book already exists";
                return(View("~/Views/Books/AddBook.cshtml"));
            }

            db.books.Add(book);
            db.SaveChanges();
            var modelquery = db.books.Select(x => new Books
            {
                Title           = x.title,
                Publisher       = x.publisher,
                PublicationDate = x.pub_date,
                Id = x.id
            }).ToList();

            return(View("~/Views/Books/BooksView.cshtml", modelquery));
        }
Ejemplo n.º 4
0
        public List <book> getbycid(int cid, int page, int size)
        {
            try
            {
                String query = "SELECT * FROM book inner join book_categories on book.id=book_categories.bookid\n"
                               + "inner join account account on account.userName=book.createby where book_categories.categoryid='" + cid + "'\n"
                               + "ORDER BY book.id OFFSET (" + page + "*" + size + "-" + size + ") ROWS FETCH NEXT " + size + " ROWS ONLY";


                DataTable dataTable = dataProvider.excuteQuery(query);

                List <book> list = new List <book>();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    account a = new account();
                    a.username = dataTable.Rows[i]["userName"].ToString();
                    a.fullname = dataTable.Rows[i]["displayName"].ToString();
                    book S = new book();
                    S.id           = int.Parse(dataTable.Rows[i]["id"].ToString());
                    S.shortDes     = dataTable.Rows[i]["shortdes"].ToString();
                    S.name         = dataTable.Rows[i]["name"].ToString();
                    S.des          = dataTable.Rows[i]["description"].ToString();
                    S.language     = dataTable.Rows[i]["language"].ToString();
                    S.img          = dataTable.Rows[i]["image"].ToString();
                    S.createdby    = a;
                    S.pulishedDate = DateTime.Parse(dataTable.Rows[i]["published"].ToString());
                    //S.point = Int32.Parse(dataTable.Rows[i]["point"].ToString());
                    list.Add(S);
                }

                return(list);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Searching" + ex.Message);
            }
            return(null);
        }
Ejemplo n.º 5
0
    public static bool savely(book ly)
    {
        SqlConnection conn = DB.createdb();

        conn.Open();
        try
        {
            //SqlCommand cmd = new SqlCommand("insert into book(username,sex,qq,email,face,adddate,body,ishidden,homepage) values(@username,@sex,@qq,@email,@face,@adddate,@body,@ishidden,@homepage)", conn);
            SqlCommand cmd = new SqlCommand("insert into book(username,sex,body,qq,email,face,adddate,ishidden,homepage) values(@username,@sex,@body,@qq,@email,@face,@adddate,@ishidden,@homepage)", conn);
            cmd.Parameters.Add(new SqlParameter("@username", SqlDbType.NVarChar, 20));
            cmd.Parameters["@username"].Value = ly.username;
            cmd.Parameters.Add(new SqlParameter("@sex", SqlDbType.NVarChar, 4));
            cmd.Parameters["@sex"].Value = ly.sex;
            cmd.Parameters.Add("@body", SqlDbType.NVarChar, 500);
            cmd.Parameters["@body"].Value = ly.body;
            cmd.Parameters.Add("@qq", SqlDbType.NVarChar, 10);
            cmd.Parameters["@qq"].Value = ly.qq;
            cmd.Parameters.Add("@email", SqlDbType.NVarChar, 20);
            cmd.Parameters["@email"].Value = ly.email;
            cmd.Parameters.Add("@face", SqlDbType.NVarChar, 10);
            cmd.Parameters["@face"].Value = ly.face;
            cmd.Parameters.Add("@adddate", SqlDbType.DateTime, 8);
            cmd.Parameters["@adddate"].Value = System.DateTime.Now.ToLongTimeString();

            cmd.Parameters.Add("@ishidden", SqlDbType.Bit, 1);
            cmd.Parameters["@ishidden"].Value = ly.ishide;
            cmd.Parameters.Add("@homepage", SqlDbType.NVarChar, 50);
            cmd.Parameters["@homepage"].Value = ly.homepage;
            cmd.ExecuteNonQuery();
            conn.Close();
            return(true);
        }
        catch
        {
            conn.Close();
            return(false);
        }
    }
Ejemplo n.º 6
0
        protected void ButtonClearList_Click(object sender, EventArgs e)
        {
            Session["Student_Id"] = null;
            BookIssues            = new List <book_issue>();
            NameObjectCollectionBase.KeysCollection Keys = Session.Keys;
            for (int i = 0; i < Keys.Count; i++)
            {
                string key = Keys[i];
                if (key.Contains("BookIssues_"))
                {
                    Session[key] = null;
                    Book         = null;
                }

                if (key.Contains("CurrentBook_"))
                {
                    Session[key] = null;
                    BookRecord   = null;
                }

                if (key.Contains("CurrentBookRecord_"))
                {
                    Session[key] = null;
                }
            }

            /*Session["BookIssues_"+CurrentStudent.id] = null;
             * Book = null;
             * Session["CurrentBook_"+CurrentStudent.id]= null;
             * BookRecord = null;
             * Session["CurrentBookRecord_"+CurrentStudent.id] = null;*/
            TextBoxStudentID.Text = "";
            PanelBookIssues.Controls.Clear();
            PanelBookList.Controls.Clear();
            InitPage();
            ShowCurrentBook("");
            LabelRecordList.Text = "";
        }
Ejemplo n.º 7
0
        public bool Delete(long idbook)
        {
            book book = GetByID(idbook);

            try
            {
                if (book != null)
                {
                    book.updatedat = DateTime.Now;
                    book.status    = -1;
                    db.SaveChanges();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
 public void Update(book entity)
 {
     _iConnection.ExecuteScalar <book>(
         "UPDATE book SET author=@author, publisher=@publisher, url=@url, entrytype=@entrytype, address=@address, edition=@edition ,bibtexkey=@bibtexkey," +
         "month=@month, note=@note, series=@series," +
         "title=@title, volume=@volume, year=@year where ID = @ID", new
     {
         entity.series,
         entity.entrytype,
         entity.bibtexkey,
         entity.author,
         entity.publisher,
         entity.edition,
         entity.month,
         entity.note,
         entity.address,
         entity.url,
         entity.title,
         entity.volume,
         entity.year,
         entity.ID
     });
 }
Ejemplo n.º 9
0
        public IHttpActionResult Deletebook(int id)
        {
            book book = db.books.Find(id);
            var  ab   = db.authors_books.FirstOrDefault(x => x.author_id == id);

            while (ab != null)
            {
                db.authors_books.Remove(ab);
                db.SaveChanges();
                ab = db.authors_books.FirstOrDefault(x => x.author_id == id);
            }

            if (book == null)
            {
                return(NotFound());
            }


            db.books.Remove(book);
            db.SaveChanges();

            return(Ok(book));
        }
Ejemplo n.º 10
0
        public ActionResult OnPostOffer(int id)
        {
            Book            = bd.objectBook(id);
            carts.IdBook    = id;
            carts.login     = HttpContext.User.Identity.Name;
            carts.NameBook  = Book.Name;
            carts.Author    = Book.Author;
            carts.count     = count;
            carts.priceBook = Book.price;
            carts.Photo     = Book.PhotoPath;
            carts.FullPrice = Book.price * count;
            carts.status    = 0;
            carts.ID        = Guid.NewGuid().ToString();
            Book.count     -= count;

            bd.update(Book);
            CR.Offer(carts);
            bd.Save();
            CR.save();


            return(RedirectToPage("ViewBooks"));
        }
Ejemplo n.º 11
0
        public ActionResult delete(int id)
        {
            var books = new List <book>();

            books.Add(new book(1, "cuon sach thu 1", "tacgia1", "/Content/images/IMG_0486.JPG"));
            books.Add(new book(2, "cuon sach thu 2", "tacgia2", "/Content/images/IMG_0487.JPG"));
            books.Add(new book(3, "cuon sach thu 3", "tacgia2", "/Content/images/IMG_0488.JPG"));
            book b = new book();

            foreach (book i in books)
            {
                if (i.Id == id)
                {
                    b = i;
                    break;
                }
            }
            if (b == null)
            {
                return(HttpNotFound());
            }
            return(View(b));
        }
Ejemplo n.º 12
0
        private static BookModel BookModelFromEntity(book book)
        {
            BookModel bm = new BookModel
            {
                author = new PersonModel
                {
                    age  = book.author.birth_year,
                    name = book.author.name,
                    sex  = "male"
                },
                name        = book.name,
                description = book.description,
                isbn        = book.isbn,
                jenres      = book.jenres.Split(',').Select(s => (BookJenre)Enum.Parse(typeof(BookJenre), s)).ToList(),
                depositCost = book.depositCost,
                rentCost    = book.rentCost,
                year        = book.year,
                pages       = book.pages,
                dbId        = book.idBook
            };

            return(bm);
        }
Ejemplo n.º 13
0
        private void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                Int32 pagecount = Int32.Parse(tb_Pagecount.Text);
                Int32 year      = Int32.Parse(tb_Year.Text);

                book b = new book();
                b.title     = tb_Title.Text;
                b.author    = tb_Author.Text;
                b.isbn      = tb_ISBN.Text;
                b.publisher = tb_Publisher.Text;
                b.pages     = pagecount;
                b.year      = year;
                b.id        = b.author.Substring(0, 2) + b.title.Substring(0, 3);
                bmc.addBook(b);
                Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Could not add book: \n" + ex.ToString());
            }
        }
Ejemplo n.º 14
0
 public HttpResponseMessage Post([FromBody] book bookModel)
 {
     if (!ModelState.IsValid)
     {
         var resposnse = Request.CreateResponse(HttpStatusCode.BadRequest);
         resposnse.Content = new StringContent(JsonConvert.SerializeObject(ModelState), Encoding.UTF8, "application/json");
         return(resposnse);
     }
     else
     {
         //Use commented code to insert value explicitely into the identity column
         //var p = dbContext.books.OrderByDescending(x => x.bookId).FirstOrDefault();
         //bookModel.bookId = p == null ? 0 : p.bookId + 1;
         //dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.books ON");
         bookModel.readbook = bookModel.readbook == null || bookModel.readbook == "" ? "No" : bookModel.readbook;
         dbContext.books.Add(bookModel);
         dbContext.SaveChanges();
         // dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.books OFF");
         var response = Request.CreateResponse(HttpStatusCode.OK);
         response.Content = new StringContent(JsonConvert.SerializeObject(bookModel), Encoding.UTF8, "application/json");
         return(response);
     }
 }
Ejemplo n.º 15
0
        public ActionResult editbook(int id)
        {
            var books = new List <book>();

            books.Add(new book(1, "cuon sach thu 1", "tacgia1", "/Content/images/IMG_0486.JPG"));
            books.Add(new book(2, "cuon sach thu 2", "tacgia2", "/Content/images/IMG_0487.JPG"));
            books.Add(new book(3, "cuon sach thu 3", "tacgia3", "/Content/images/IMG_0488.JPG"));
            book book = new book();

            foreach (book b in books)
            {
                if (b.Id == id)
                {
                    book = b;
                    break;
                }
                if (book == null)
                {
                    return(HttpNotFound());
                }
            }
            return(View(book));
        }
    protected void addly_Click(object sender, EventArgs e)
    {
        book binbin = new book();

        binbin.username = Server.HtmlEncode(this.username.Text);
        binbin.email    = this.email.Text;
        binbin.qq       = this.qq.Text;
        binbin.homepage = this.homepage.Text;
        if (this.Radboy.Checked)
        {
            binbin.sex  = "men";
            binbin.face = "boy";
        }
        else
        {
            binbin.sex  = "female";
            binbin.face = "gril";
        }
        binbin.body = this.lybody.Text;
        if (this.ishde.Checked)
        {
            binbin.ishide = true;
        }
        else
        {
            binbin.ishide = false;
        }
        Label1.Text = binbin.ishide.ToString();
        if (saveinfo.savely(binbin))
        {
            Response.Redirect("lyb.aspx");
        }
        else
        {
            Response.Write("<script>alert('Message failed, server error!');location.herf='lyb.aspx'");
        }
    }
Ejemplo n.º 17
0
        //Add
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (ValidateEmptyTextBox(1))
            {
                try
                {
                    projectEntities project = new projectEntities();

                    book book = new book();
                    book.ISBN          = textBoxISBN.Text;
                    book.Title         = textBoxTitle.Text;
                    book.UnitPrice     = Convert.ToDouble(textBoxPrice.Text);
                    book.YearPublished = publishYear.Value.Date;
                    book.QOH           = Convert.ToInt32(textBoxQoh.Text);
                    book.AuthorID      = Convert.ToInt32(textBoxAuthorID.Text);
                    book.PublishID     = Convert.ToInt32(textBoxPublishID.Text);
                    book.CategoryID    = Convert.ToInt32(textBoxCategoryID.Text);


                    project.books.Add(book);

                    project.SaveChanges();
                    this.DisplayBookInformation();
                    MessageBox.Show("Recored Inserted..");
                    this.ClearTextBox();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Recored Is Not Inserted..\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.ClearTextBox();
                }
            }
            else
            {
                MessageBox.Show("Please Enter Values. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 18
0
    public static void Main()
    {
        book[] books = new book[10000];
        int    count = 0;

        bool finished = false;

        do
        {
            switch (ShowMenuAndGetOption())
            {
            case "1": Add(ref books, ref count); break;

            case "2": ShowAll(books, count); break;

            case "3": Search(books, count); break;

            case "0": finished = true; break;

            default: WarnAboutWrongOption(); break;
            }
        }while (!finished);
        Console.WriteLine("Bye!");
    }
Ejemplo n.º 19
0
    protected void addly_Click(object sender, EventArgs e)
    {
        book binbin = new book();

        binbin.username = Server.HtmlEncode(this.username.Text);

        binbin.homepage = this.homepage.Text;
        if (this.Radboy.Checked)
        {
            binbin.sex  = "男";
            binbin.face = "boy";
        }
        else
        {
            binbin.sex  = "女";
            binbin.face = "gril";
        }
        binbin.body = Request.Form["content"];
        if (this.ishde.Checked)
        {
            binbin.ishide = true;
        }
        else
        {
            binbin.ishide = false;
        }
        Label1.Text = binbin.ishide.ToString();
        if (saveinfo.savely(binbin))
        {
            Response.Redirect("lybb.aspx");
        }
        else
        {
            Response.Write("<script>alert('留言失败,服务器错误!');location.herf='lyb.aspx'");
        }
    }
Ejemplo n.º 20
0
        public override object Update(object Obj)
        {
            Refresh();
            book book   = (book)Obj;
            book DBBook = (book)GetById(book.id);

            if (DBBook == null)
            {
                return(null);
            }
            book CleanBook = (book)ObjectUtil.GetObjectValues(new string[]
            {
                "id", "title", "page", "review", "category_id", "publisher_id", "isbn", "author_id"
            }, book);

            if (CleanBook.page == null)
            {
                CleanBook.page = 0;
            }
            //   dbEntities.Entry(book).CurrentValues.
            dbEntities.Entry(DBBook).CurrentValues.SetValues(CleanBook);
            dbEntities.SaveChanges();
            return(book);
        }
        public ActionResult choose(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            book book     = db.books.Find(id);
            book tempbook = new book
            {
                ID            = db2.books.Select(e => e.ID).Max() + 1,
                title         = book.title,
                author        = book.author,
                press         = book.press,
                lenderID      = book.lenderID,
                lendername    = book.lendername,
                lendercontact = book.lendercontact
            };

            db2.books.Add(tempbook);
            db2.SaveChanges();
            db.books.Remove(book);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 22
0
        public string Update(int id, [FromBody] book i)
        {
            var b = (from t in db.books
                     where t.bid == id
                     select t).SingleOrDefault();

            if (b == null)
            {
                throw new Exception("Book Id Invalid");
            }
            else
            {
                b.bname  = i.bname;
                b.bgener = i.bgener;
                b.bprice = i.bprice;

                var res = db.SaveChanges();
                if (res > 0)
                {
                    return("Data Uploaded");
                }
            }
            return("Error Updating Data");
        }
Ejemplo n.º 23
0
        // POST api/apiBook
        public IHttpActionResult Post(book book)
        {
            if (book == null || string.IsNullOrWhiteSpace(book.title) || string.IsNullOrWhiteSpace(book.description) || string.IsNullOrWhiteSpace(book.publication_date.ToString()) || string.IsNullOrWhiteSpace(book.isbn))
            {
                return(Json(new { bookCreationSuccess = false, errorMessage = "Braki w następujących polach: tytuł, opis, data publikacji, isbn" }));
            }

            var credentials = Request.Headers.FirstOrDefault(x => x.Key.Equals("Authorization")).Value.ToList()[0];

            if (credentials != null)
            {
                var            loggedAuthor    = credentials.Split('=')[0];
                var            token           = credentials.Split('=')[1];
                var            authorFromToken = JWTHelper.ValidateToken(token);
                var            groupId         = db.author.FirstOrDefault(x => x.login == authorFromToken).group_id;
                List <setting> settings        = db.group.FirstOrDefault(x => x.group_id == groupId).group_setting.Select(x => x.setting).ToList();

                if (loggedAuthor == authorFromToken && settings.Any(x => x.name == "book_create"))
                {
                    book.status = StatusesEnum.ACTIVE.ToString();
                    var newBook = db.book.Add(book);

                    var log = db.log.Add(new log()
                    {
                        book_id    = book.book_id,
                        author_id  = book.author_id,
                        event_name = LogTypesEnum.CREATE.ToString(),
                        event_date = DateTime.Now
                    });

                    db.SaveChanges();
                    return(Json(new { bookCreationSuccess = true }));
                }
            }
            return(Json(new { bookCreationSuccess = false, errorMessage = "Wystąpił błąd. Przepraszamy za kłopoty techniczne" }));
        }
Ejemplo n.º 24
0
        public ActionResult Add(book model)
        {
            try
            {
                DbModel db = new DbModel();

                if (ModelState.IsValid)
                {
                    model.IsActive = 1;
                    db.book.Add(model);
                    db.SaveChanges();
                    Request.Flash("success", "Add Success");
                    return(Redirect("~/book"));
                }

                ViewBag.IdCategory = new SelectList(db.category.Where(d => d.IsActive == 1), "IdCategory", "NameCategory");
                return(View(model));
            }
            catch (Exception ex)
            {
                Request.Flash("error", ex.Message);
                return(Redirect("~/book"));
            }
        }
        public ActionResult Create([Bind(Include = "book_id,title,edition,price,publication_id,author_id,subcategory_id,pages,description,rate,availabilty,tags,uploadedImage,uploadedFile")] book book)
        {
            if (ModelState.IsValid)
            {
                book.add_date = DateTime.Now.ToString();                                                    // Data
                var userName = User.Identity.GetUserName();
                book.member_id = db.users.Where(x => x.UserName == userName).Select(x => x.Id).FirstOrDefault();

                // Uplaod Photo =======================================================================================================
                string ImageName      = Path.GetFileNameWithoutExtension(book.uploadedImage.FileName); // get name
                string ImageExtension = Path.GetExtension(book.uploadedImage.FileName);                // get extension
                ImageName  = ImageName + '_' + DateTime.Now.ToString("yymmssfff") + ImageExtension;    // Not To Repeat
                book.photo = "~/Uploads/Photos/books/" + ImageName;                                    // Save To DB
                ImageName  = Path.Combine(Server.MapPath("~/Uploads/Photos/books/"), ImageName);       // Combine To Local Folder
                book.uploadedImage.SaveAs(ImageName);                                                  // Move it

                // Uplaod File =======================================================================================================
                string FileName      = Path.GetFileNameWithoutExtension(book.uploadedFile.FileName);        // get name
                string FileExtension = Path.GetExtension(book.uploadedFile.FileName);                       // get extension
                FileName  = FileName + '_' + DateTime.Now.ToString("yymmssfff") + FileExtension;            // Not To Repeat
                book.File = "~/Uploads/Books/" + FileName;                                                  // Save To DB
                FileName  = Path.Combine(Server.MapPath("~/Uploads/Books/"), FileName);                     // Combine To Local Folder
                book.uploadedFile.SaveAs(FileName);                                                         // Move it

                db.books.Add(book);
                db.SaveChanges();
                TempData["Success"] = "Created Successfully!";
                return(RedirectToAction("Index"));
            }

            ViewBag.author_id      = new SelectList(db.authors, "author_id", "first_name", book.author_id);
            ViewBag.publication_id = new SelectList(db.publications, "publication_id", "name", book.publication_id);
            ViewBag.subcategory_id = new SelectList(db.subcategories, "subcategory_id", "subcategory_name", book.subcategory_id);
            ViewBag.member_id      = new SelectList(db.users, "Id", "first_name", book.member_id);
            return(View(book));
        }
Ejemplo n.º 26
0
        private void btn_save_Click(object sender, EventArgs e)
        {
            // reset label error trước khi validate
            foreach (string n in arrLabelNameError)
            {
                this.Controls.Find(n, true)[0].Text = "";
            }

            // Tạo đối tượng book
            book b = new book();

            b.BookCode = Functions.randomString(8); // Mã sách sẽ được tạo ngẫu nhiên bằng chuỗi với độ dài 8
            b.BookName = txt_bookName.Text.Replace("'", "''");
            b.Price    = 0;
            if (!string.IsNullOrEmpty(txt_price.Text))
            {
                try
                {
                    b.Price = Math.Abs(Convert.ToInt32(txt_price.Text));
                }
                catch
                {
                    lbl_error_price.Text = "Giá sách phải là số nguyên dương";
                }
            }
            b.Category     = cbx_category.Text.Replace("'", "''");
            b.Author       = txt_author.Text.Replace("'", "''");
            b.PublishingBy = txt_publishingBy.Text.Replace("'", "''");



            // Để kiểm tra các dữ liệu phù hợp thiết lập bởi Attribute bên Model không, thì dùng lớp ValidationContext
            ValidationContext context = new ValidationContext(b);

            // results - lưu danh sách ValidationResult, kết quả kiểm tra
            var result = new List <ValidationResult>();

            // thực hiện kiểm tra dữ liệu
            bool valid = Validator.TryValidateObject(b, context, result, true);

            if (valid == false)
            {
                foreach (ValidationResult r in result)
                {
                    // Tạo controlName bằng string
                    string controlName = "lbl_error_" + r.MemberNames.First();
                    // Tìm control thông qua key string và gán messError và thay đổi màu cho label error
                    this.Controls.Find(controlName, true)[0].Text      = r.ErrorMessage;
                    this.Controls.Find(controlName, true)[0].ForeColor = Color.Red;
                }
            }
            else
            {
                // Không tồn tại mã sách thì là thêm mới
                if (string.IsNullOrEmpty(this.bookCode))
                {
                    if (busBook.addBook(b) == true)
                    {
                        MessageBox.Show("Thêm mới sách thành công", "Thành Công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Thêm mới sách thất bại", "Thất Bại", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    b.BookCode = this.bookCode;
                    if (busBook.updateBook(b) == true)
                    {
                        MessageBox.Show("Cập nhật sách thành công", "Thành Công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Cập nhật sách thất bại", "Thất Bại", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Ejemplo n.º 27
0
 public int insert(book b)
 {
     return(this.data.insert(b));
 }
Ejemplo n.º 28
0
        public DataTable booking(book ocr)
        {
            DataTable      dt          = new DataTable();
            LogTraceWriter traceWriter = new LogTraceWriter();
            SqlConnection  conn        = new SqlConnection();
            StringBuilder  str         = new StringBuilder();

            try
            {
                traceWriter.Trace(Request, "0", TraceLevel.Info, "{0}", "booking....");

                str.Append("Username:"******",");
                str.Append("PhoneNumber:" + ocr.PhoneNumber + ",");
                str.Append("EmailId:" + ocr.EmailId + ",");
                str.Append("src:" + ocr.src + ",");
                str.Append("dest:" + ocr.dest + ",");
                str.Append("Gender:" + ocr.Gender + ",");

                traceWriter.Trace(Request, "0", TraceLevel.Info, "{0}", "Input sent...." + str.ToString());

                conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["btposdb"].ToString();

                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "prebooking";

                cmd.Connection = conn;

                SqlParameter f = new SqlParameter("@flag", SqlDbType.VarChar);
                f.Value = ocr.flag;
                cmd.Parameters.Add(f);


                SqlParameter q = new SqlParameter("@Id", SqlDbType.Int);
                q.Value = ocr.Id;
                cmd.Parameters.Add(q);

                SqlParameter q1 = new SqlParameter("@Username", SqlDbType.VarChar, 50);
                q1.Value = ocr.Username;
                cmd.Parameters.Add(q1);

                SqlParameter c = new SqlParameter("@PhoneNumber", SqlDbType.VarChar, 20);
                c.Value = ocr.PhoneNumber;
                cmd.Parameters.Add(c);

                SqlParameter e = new SqlParameter("@EmailId", SqlDbType.VarChar, 50);
                e.Value = ocr.EmailId;
                cmd.Parameters.Add(e);



                SqlParameter b = new SqlParameter("@src", SqlDbType.VarChar, 50);
                b.Value = ocr.src;
                cmd.Parameters.Add(b);

                SqlParameter p = new SqlParameter("@dest", SqlDbType.VarChar, 50);
                p.Value = ocr.dest;
                cmd.Parameters.Add(p);

                SqlParameter m = new SqlParameter("@Gender", SqlDbType.VarChar, 50);
                m.Value = ocr.Gender;
                cmd.Parameters.Add(m);

                SqlParameter t = new SqlParameter("@Age", SqlDbType.Int);
                t.Value = ocr.Age;
                cmd.Parameters.Add(t);

                SqlParameter e2 = new SqlParameter("@Blocked", SqlDbType.VarChar, 50);
                e2.Value = ocr.Blocked;
                cmd.Parameters.Add(e2);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                traceWriter.Trace(Request, "0", TraceLevel.Info, "{0}", "booking successful....");
            }
            catch (Exception ex)
            {
                traceWriter.Trace(Request, "0", TraceLevel.Error, "{0}", "booking...." + ex.Message.ToString());
                //throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
                dt.Columns.Add("Code");
                dt.Columns.Add("description");
                DataRow dr = dt.NewRow();
                dr[0] = "ERR001";
                dr[1] = ex.Message;
                dt.Rows.Add(dr);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
                SqlConnection.ClearPool(conn);
            }
            return(dt);
        }
Ejemplo n.º 29
0
 public int update(book b)
 {
     return(this.data.update(b));
 }
Ejemplo n.º 30
0
 public int CountBook(int id)
 {
     Books = BR.objectBook(id);
     return(Books.count);
 }