public IQueryable<BookModel> booksGridView_GetData()
        {
            try
            {
                LibrarySystemEntities db = new LibrarySystemEntities();
                var books = (from b in db.Books.ToList()
                             select new BookModel()
                             {
                                 Id = b.id,
                                 Title = b.title.Substring(0, Math.Min(b.title.Length, 20)) + "...",
                                 Author = b.author,
                                 Description = b.description,
                                 Isbn = b.isbn,
                                 WebSite = b.webSite,
                                 Category = db.Categories.Find(b.categoryId).name
                             });
                return books.AsQueryable<BookModel>();
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }

            return null;
        }
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<Categories> catsGridView_GetData()
        {
            try
            {
                LibrarySystemEntities db = new LibrarySystemEntities();
                return db.Categories.OrderBy(q => q.id);
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                ErrorSuccessNotifier.AddErrorMessage(exceptionMessage + " " + ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }

            return null;
        }
        protected void SaveBtn_Click(object sender, CommandEventArgs e)
        {
            try
            {
                var id = Convert.ToInt32(e.CommandArgument);

                LibrarySystemEntities db = new LibrarySystemEntities();
                var currCat = db.Categories.FirstOrDefault(c => c.id == id);

                currCat.name = catName.Text;
                db.SaveChanges();
                Response.Redirect("~/Admin/EditCategories.aspx");
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                ErrorSuccessNotifier.AddErrorMessage(exceptionMessage + " " + ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }
        }
        protected void Yes_Click(object sender, EventArgs e)
        {
            var context = new LibrarySystemEntities();

            Button but = (Button)sender;
            int id = int.Parse(but.CommandArgument);


            var category = context.Categories.Find(id);

            context.Categories.Remove(category);

            try
            {
                context.SaveChanges();
                this.EditCategoriesList.DataBind();
                this.DeleteForm.Visible = false;
                ErrorSuccessNotifier.AddSuccessMessage("Category Deleted");
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex);
                ErrorSuccessNotifier.ShowAfterRedirect = true;
                Response.Redirect("../EditCategories.aspx");

            }
        }
        protected void EditBook_Command(object sender, CommandEventArgs e)
        {
            this.PanelCreateEdit.Visible = true;
            this.LinkButtonEditSave.Visible = true;
            this.LinkButtonCreateConfirm.Visible = false;
            this.LinkButtonCreateNewBook.Visible = false;
            this.LiteralBookToEditId.Text = e.CommandArgument.ToString();

            var bookId = Convert.ToInt32(e.CommandArgument);
            var context = new LibrarySystemEntities();
            var book = context.Books.Include(b => b.Category).FirstOrDefault(b => b.BookId == bookId);
            if (book == null)
            {
                ErrorSuccessNotifier.AddErrorMessage(
                    "An unexpected error occurred! The book you want to edit was not found...");
            }
            else
            {
                this.TextBoxCreateEditBookTitle.Text = book.Title;
                this.TextBoxCreateEditBookAuthors.Text = book.Authors;
                this.TextBoxCreateEditBookDescription.Text = book.Description;
                this.TextBoxCreateEditBookIsbn.Text = book.ISBN;
                this.TextBoxCreateEditBookWebSite.Text = book.WebSite;
                this.DropDownListBookCategories.SelectedValue = book.Category.Name;
                this.LinkButtonCreateConfirm.Visible = false;
            }
        }
        protected void LinkButtonCreateConfirm_Click(object sender, EventArgs e)
        {
            var categoryName = this.TextBoxCreateCategoryName.Text.Trim();
            if (categoryName.Length < 2)
            {
                ErrorSuccessNotifier.AddErrorMessage("Category name must consist of at least 2 symbols!");
                return;
            }

            var context = new LibrarySystemEntities();
            if (context.Categories.Any(c => c.Name == categoryName))
            {
                ErrorSuccessNotifier.AddErrorMessage("Category with this name already exists!");
                return;
            }

            var newCategory = new Category();
            newCategory.Name = categoryName;
            context.Categories.Add(newCategory);

            try
            {
                context.SaveChanges();
                this.GridViewCategories.DataBind();
                this.TextBoxCreateCategoryName.Text = string.Empty;
                ErrorSuccessNotifier.AddSuccessMessage("Category successfully created!");
            }
            catch (Exception exc)
            {
                ErrorSuccessNotifier.AddErrorMessage(exc);
            }
        }
        protected void CreateCategoryButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            string categoryName = this.CreateCategoryField.Text;

            if (string.IsNullOrWhiteSpace(categoryName))
            {
                ErrorSuccessNotifier.AddErrorMessage("Category name cannot be empty");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            if (categoryName.Length < 3 || categoryName.Length > 100)
            {
                ErrorSuccessNotifier.AddErrorMessage("Category length should be  between 3 and 100 symbols");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            Category newCategory = new Category();
            newCategory.CategoryName = categoryName;

            context.Categories.Add(newCategory);
            context.SaveChanges();

            ErrorSuccessNotifier.AddSuccessMessage("Category created!");
            this.Response.Redirect("~/Admin/EditCategories.aspx");
        }
        protected void CreateBtn_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var context = new LibrarySystemEntities();
                string title = this.CategoryTitleTb.Text;
                Category category = new Category()
                {
                    Name = title
                };

                try
                {
                    context.Categories.Add(category);
                    context.SaveChanges();
                    this.CategoryTitleTb.Text = "";
                    this.InsertForm.Visible = false;
                    this.EditCategoriesList.DataBind();

                    ErrorSuccessNotifier.AddSuccessMessage("Category created");
                }
                catch (Exception ex)
                {

                    ErrorSuccessNotifier.AddErrorMessage(ex);
                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    Response.Redirect("../EditCategories.aspx");
                }
            }

        }
 // The id parameter name should match the DataKeyNames value set on the control
 public void GridViewBooks_UpdateItem(int id)
 {
     LibrarySystemEntities context = new LibrarySystemEntities();
     var book = context.Books.Find(id);
     InitializeEditPanel(id, context, book);
     HideAllPanels();
     this.PanelEditBook.Visible = true;
 }
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<Book> BooksListView_GetData()
        {
            var context = new LibrarySystemEntities();

            var books = context.Books;

            return books;
        }
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<Category> EditCategoriesList_GetData()
        {
            var context = new LibrarySystemEntities();

            var categories = context.Categories;

            return categories;
        }
 // The id parameter name should match the DataKeyNames value set on the control
 public void GridViewBooks_DeleteItem(int id)
 {
     LibrarySystemEntities context = new LibrarySystemEntities();
     var book = context.Books.Find(id);
     HideAllPanels();
     this.HiddenFieldDeleteBookId.Value = id.ToString();
     this.TextBoxDeleteBookTitle.Text = book.Title;
     this.PanelDeleteBook.Visible = true;
 }
 protected void LinkButtonCreateNewBook_Click(object sender, EventArgs e)
 {
     LibrarySystemEntities context = new LibrarySystemEntities();
     ClearCreatePanelFields();
     HideAllPanels();
     this.DropDownListCreateBookCategory.DataSource = context.Categories.ToList();
     this.DropDownListCreateBookCategory.DataBind();
     this.PanelCreateBook.Visible = true;
 }
 // The id parameter name should match the DataKeyNames value set on the control
 public void GridViewCategories_UpdateItem(int id)
 {
     LibrarySystemEntities context = new LibrarySystemEntities();
     var cat = context.Categories.Find(id);
     HideAllPanels();
     this.LinkButtonCreateNewCategory.Visible = false;
     this.HiddenFieldEditCategoryId.Value = id.ToString();
     this.TextBoxEditCategoryName.Text = cat.Title;
     this.PanelEditCategory.Visible = true;
 }
        protected void CreateNewBookBtn_Click(object sender, EventArgs e)
        {
            this.DeleteForm.Visible = false;
            this.EditForm.Visible = false;
            this.InsertForm.Visible = true;

            var context = new LibrarySystemEntities();
            var categories = context.Categories;

            this.AllCategoriesList.DataSource = categories.ToList();
            this.AllCategoriesList.DataBind();
        }
        protected void CreateBookButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            string title = this.TextBoxTitle.Text;
            string author = this.TextBoxAuthor.Text;
            string isbn = this.TextBoxISBN.Text;
            string webSite = this.TextBoxWebSite.Text;
            string description = this.TextBoxDescription.Text;
            int categoryIndex = int.Parse(this.DropDownListCategory.SelectedValue);

            if (string.IsNullOrWhiteSpace(title))
            {
                ErrorSuccessNotifier.AddErrorMessage("Title cannot be empty");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            if (string.IsNullOrWhiteSpace(author))
            {
                ErrorSuccessNotifier.AddErrorMessage("Author cannot be empty");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            if (title.Length < 3 || title.Length > 256)
            {
                ErrorSuccessNotifier.AddErrorMessage("Title's length should be between 3 and 256 symbols");
                this.Response.Redirect("~/Admin/EditBooks.aspx");
            }

            if (author.Length < 3 || author.Length > 100)
            {
                ErrorSuccessNotifier.AddErrorMessage("Author's length should be between 3 and 100 symbols");
                this.Response.Redirect("~/Admin/EditBooks.aspx");
            }

            var category = context.Categories.FirstOrDefault(c => c.Id == categoryIndex);

            Book newBook = new Book();
            newBook.Title = title;
            newBook.Author = author;
            newBook.ISBN = isbn;
            newBook.WebSite = webSite;
            newBook.Description = description;
            newBook.Category = category;

            category.Books.Add(newBook);

            context.SaveChanges();

            ErrorSuccessNotifier.AddSuccessMessage("Book created!");
            this.Response.Redirect("~/Admin/EditBooks.aspx");
        }
        protected void ButtonDelete_Click(object sender, EventArgs e)
        {
            this.DeleteForm.Visible = true;
            this.InsertForm.Visible = false;
            this.EditForm.Visible = false;
            Button but = (Button)sender;
            int id = int.Parse(but.CommandArgument);

            this.Yes.CommandArgument = id.ToString();
            var context = new LibrarySystemEntities();
            var book = context.Books.Find(id);
            this.DeleteCategoryName.Text = book.Title;
        }
        protected void DeleteCategoryPanelButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();
            int categoryId = int.Parse(e.CommandArgument.ToString());
            var category = context.Categories.FirstOrDefault(c => c.Id == categoryId);

            if (category != null)
            {
                this.DeleteCategoryField.Text = category.CategoryName;
                this.DeleteCategoryPanel.Visible = true;
                this.EditCategoryPanel.Visible = false;
                this.CreateCategoryPanel.Visible = false;

                this.DeleteCategoryButton.CommandArgument = categoryId.ToString();
            }
        }
 public IQueryable<BookViewModel> GridViewBooks_GetData()
 {
     var context = new LibrarySystemEntities();
     var books = context.Books.Include(b => b.Category).OrderBy(b => b.BookId).Select(b =>
         new BookViewModel()
         {
             BookId = b.BookId,
             Title = b.Title,
             Authors = b.Authors,
             Description = b.Description,
             ISBN = b.ISBN,
             WebSite = b.WebSite,
             Category = b.Category.Name
         });
     return books;
 }
        protected void DeleteCategoryButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            int categoryId = int.Parse(e.CommandArgument.ToString());
            var category = context.Categories.FirstOrDefault(c => c.Id == categoryId);

            var currentCategoryBooks = category.Books;

            context.Books.RemoveRange(currentCategoryBooks);

            context.Categories.Remove(category);
            context.SaveChanges();

            ErrorSuccessNotifier.AddSuccessMessage("Category deleted!");
            this.Response.Redirect("~/Admin/EditCategories.aspx");
        }
 protected void LinkButtonDoDelete_Click(object sender, EventArgs e)
 {
     try
     {
         LibrarySystemEntities context = new LibrarySystemEntities();
         var bookId = Convert.ToInt32(this.HiddenFieldDeleteBookId.Value);
         var book = context.Books.Find(bookId);
         context.Books.Remove(book);
         context.SaveChanges();
         HideAllPanels();
         this.GridViewBooks.DataBind();
         ErrorSuccessNotifier.AddSuccessMessage("Book deleted.");
     }
     catch (Exception ex)
     {
         ErrorSuccessNotifier.AddErrorMessage(ex);
     }
 }
 protected void LinkButtonDoDelete_Click(object sender, EventArgs e)
 {
     try
     {
         LibrarySystemEntities context = new LibrarySystemEntities();
         var catId = Convert.ToInt32(this.HiddenFieldDeleteCategoryId.Value);
         var cat = context.Categories.Find(catId);
         context.Books.RemoveRange(cat.Books); // Remove all books for this caregory
         context.Categories.Remove(cat);
         context.SaveChanges();
         HideAllPanels();
         this.GridViewCategories.DataBind();
         ErrorSuccessNotifier.AddSuccessMessage("Category deleted.");
     }
     catch (Exception ex)
     {
         ErrorSuccessNotifier.AddErrorMessage(ex);
     }
 }
        protected void DeleteCategory_Command(object sender, CommandEventArgs e)
        {
            this.PanelDelete.Visible = true;
            this.LinkButtonCreateNewCategory.Visible = false;
            this.LiteralCategoryToDeleteId.Text = e.CommandArgument.ToString();

            var categoryId = Convert.ToInt32(e.CommandArgument);
            var context = new LibrarySystemEntities();
            var category = context.Categories.FirstOrDefault(c => c.CategoryId == categoryId);
            if (category == null)
            {
                ErrorSuccessNotifier.AddErrorMessage(
                    "An unexpected error occurred! The category you want to delete was not found...");
            }
            else
            {
                this.TextBoxDeleteCategoryName.Text = category.Name;
            }
        }
        protected void SaveBtn_Click(object sender, CommandEventArgs e)
        {
            try
            {
                var id = Convert.ToInt32(e.CommandArgument);

                LibrarySystemEntities db = new LibrarySystemEntities();
                var currBook = db.Books.FirstOrDefault(b => b.id == id);

                currBook.title = bookTitle.Text;
                currBook.author = bookAuthor.Text;
                currBook.isbn = bookIsbn.Text;
                currBook.webSite = bookWebSite.Text;
                currBook.description = bookDescr.Text;
                currBook.categoryId = db.Categories.First(b => b.name == bookCats.SelectedItem.Value).id;
                db.SaveChanges();
                Response.Redirect("~/Admin/EditBooks.aspx");
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                ErrorSuccessNotifier.AddErrorMessage(exceptionMessage + " " + ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }
        }
        protected void ButtonEdit_Click(object sender, EventArgs e)
        {
            this.EditForm.Visible = true;
            this.DeleteForm.Visible = false;
            this.InsertForm.Visible = false;
            Button but = (Button)sender;
            int id = int.Parse(but.CommandArgument);
            this.SaveEdit.CommandArgument = id.ToString();

            var context = new LibrarySystemEntities();
            var book = context.Books.Find(id);
            var categories = context.Categories;

            this.EditBookTitleTb.Text = book.Title;
            this.EditBookAuthorTb.Text = book.Author;
            this.EditBookIsbnTb.Text = book.ISBN;
            this.EditWebSiteTb.Text = book.WebSite;
            this.EditDescriptionTa.Value = book.Description;
            this.EditAllCategories.DataSource = categories.ToList();
            this.EditAllCategories.DataBind();


        }
        protected void DeleteBookButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            int bookId = int.Parse(e.CommandArgument.ToString());
            var book = context.Books.FirstOrDefault(b => b.Id == bookId);

            context.Books.Remove(book);
            context.SaveChanges();

            ErrorSuccessNotifier.AddSuccessMessage("Book deleted!");
            this.Response.Redirect("~/Admin/EditBooks.aspx");
        }
 public IQueryable<Book> GridViewBooks_GetData()
 {
     var context = new LibrarySystemEntities();
     return context.Books.Include("Category");
 }
        protected void ShowAddBookPanel_Click(object sender, EventArgs e)
        {
            this.CreateBookPanel.Visible = true;
            this.EditBookPanel.Visible = false;
            this.DeleteBookPanel.Visible = false;

            var context = new LibrarySystemEntities();

            this.DropDownListCategory.DataSource = context.Categories.ToList();
            this.DropDownListCategory.DataBind();
        }
        protected void EditBooksPanelButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            this.DropDownListEditCategory.DataSource = context.Categories.ToList();
            this.DropDownListEditCategory.DataBind();

            int bookId = int.Parse(e.CommandArgument.ToString());
            var book = context.Books.Include("Category").FirstOrDefault(c => c.Id == bookId);

            if (book != null)
            {
                this.TextBoxEditTitle.Text = book.Title;
                this.TextBoxEditAuthor.Text = book.Author;
                this.TextBoxEditISBN.Text = book.ISBN;
                this.TextBoxEditWebSite.Text = book.WebSite;
                this.TextBoxEditDescription.Text = book.Description;
                this.DropDownListEditCategory.SelectedValue = book.CategoryId.ToString();
                this.EditBookPanel.Visible = true;
                this.CreateBookPanel.Visible = false;
                this.DeleteBookPanel.Visible = false;

                this.EditBookButton.CommandArgument = bookId.ToString();
            }
        }
        protected void EditBookButton_Command(object sender, CommandEventArgs e)
        {
            var context = new LibrarySystemEntities();

            string title = this.TextBoxEditTitle.Text;
            string author = this.TextBoxEditAuthor.Text;
            string isbn = this.TextBoxEditISBN.Text;
            string webSite = this.TextBoxEditWebSite.Text;
            string description = this.TextBoxEditDescription.Text;
            int categoryIndex = int.Parse(this.DropDownListEditCategory.SelectedValue);

            if (string.IsNullOrWhiteSpace(title))
            {
                ErrorSuccessNotifier.AddErrorMessage("Title cannot be empty");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            if (string.IsNullOrWhiteSpace(author))
            {
                ErrorSuccessNotifier.AddErrorMessage("Author cannot be empty");
                this.Response.Redirect("~/Admin/EditCategories.aspx");
            }

            if (title.Length < 3 || title.Length > 256)
            {
                ErrorSuccessNotifier.AddErrorMessage("Title's length should be between 3 and 256 symbols");
                this.Response.Redirect("~/Admin/EditBooks.aspx");
            }

            if (author.Length < 3 || author.Length > 100)
            {
                ErrorSuccessNotifier.AddErrorMessage("Author's length should be between 3 and 100 symbols");
                this.Response.Redirect("~/Admin/EditBooks.aspx");
            }

            int bookId = int.Parse(e.CommandArgument.ToString());
            var book = context.Books.Include("Category").FirstOrDefault(b => b.Id == bookId);
            var category = context.Categories.FirstOrDefault(c => c.Id == categoryIndex);

            book.Title = title;
            book.Author = author;
            book.ISBN = isbn;
            book.WebSite = webSite;
            book.Description = description;
            book.Category = category;

            context.SaveChanges();

            ErrorSuccessNotifier.AddSuccessMessage("Book modified!");
            this.Response.Redirect("~/Admin/EditBooks.aspx");
        }