コード例 #1
0
        public ActionResult Create(BookModels book)
        {
            try
            {
                using (var repo = new BookRepository())
                {
                    repo.Create(book);
                    book.Id = repo.GetBookByTitle(book.Title);
                }

                foreach (var author in book.SelectedAuthors)
                {
                    using (var repo = new BookRepository())
                    {
                        repo.BindAuthorToBook(book.Id, author);
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
コード例 #2
0
        //...................................Book Manipulated methods....................................................//

        //save book
        public async Task <long> AddNewBook(BookModels model)
        {
            Book newbook = new Book()
            {
                BookName       = model.BookName,
                AurtherName    = model.AurtherName,
                Genre          = model.Genre,
                Discription    = model.Discription,
                LanguageID     = model.LanguageID,
                TotalPage      = model.TotalPage,
                BookCoverPhoto = model.BookCoverPhoto,
                BookURL        = model.BookURL
            };

            //create a instance of BookGallery list to add all the BookGallery
            newbook.bookGallery = new List <BookGallery>();
            //add all the picture, BookID and BookGalleryID is automatically added
            foreach (var gallery in model.BookGallery)
            {
                newbook.bookGallery.Add(new BookGallery()
                {
                    //BookID and BookGalleryID is automatically provided
                    URL         = gallery.URL,
                    PictureName = gallery.PictureName
                });
            }
            await db.Books.AddAsync(newbook);

            await db.SaveChangesAsync();

            return((int)newbook.BookID);
        }
コード例 #3
0
        public async Task <IActionResult> AddBook([FromBody] BookModels _model)
        {
            var id = await _bookRepository.AddBook(_model);

            return(Ok(id));
            //return CreatedAtAction("GetBookById",new { id = id,Controller = "BookApi" } , id);
        }
コード例 #4
0
 public BareCodeBook BookInvoce(BareCodeBook barecode, BookModels bookModels)
 {
     barecode.NameModel = bookModels.Model;
     AddObjectDb.AddObjectDb adddoc = new AddObjectDb.AddObjectDb();
     barecode.Id = adddoc.AddBookAccounting(bookModels);
     return(barecode);
 }
コード例 #5
0
        public async Task <ViewResult> GetBook(long id)
        {
            Title = "Book Details";
            BookModels book = await bookRepository.GetByID(id);

            Book = book;
            return(View(book));
        }
コード例 #6
0
        //Pdf Viewer

        public async Task <ViewResult> PdfViewer(int bookId)
        {
            BookModels book = await bookRepository.GetByID(bookId);

            string filePath = Path.Combine(webHostEnvironment.WebRootPath, "BookPDF/97730ac9-f2a4-477f-a517-58508fec2bbf_Dsa.pdf");

            ViewBag.filePath = filePath;
            return(View(book));
        }
コード例 #7
0
        /// <summary>
        /// GET: /Initial/Create
        ///
        /// Show the form to create a new user
        /// </summary>
        /// <returns>
        /// Form to create a new user
        /// </returns>
        ///
        public ActionResult Create()
        {
            var model = new BookModels();

            using (var repo = new AuthorRepository())
            {
                model.AuthorList = repo.GetAll().ToList();
            }
            return(View(model));
        }
コード例 #8
0
        public async Task <int> AddBook(BookModels _model)
        {
            var books = new Books()
            {
                Title       = _model.Title,
                Description = _model.Description
            };

            _context.Books.Add(books);
            await _context.SaveChangesAsync();

            return(books.Id);
        }
コード例 #9
0
        public ActionResult Edit(int id, BookModels editBook)
        {
            try
            {
                using (var repo = new BookRepository())
                {
                    repo.Edit(editBook);
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
コード例 #10
0
 /// <summary>
 /// Deletes a specific item.
 /// </summary>
 /// <param name="item">The item being deleted.</param>
 public void DeleteItem(BaseInventoryModel item)
 {
     // Remove the item from their respective model collection.
     if (item is MovieModel movieModel)
     {
         MovieModels.Remove(movieModel);
     }
     else if (item is BookModel bookModel)
     {
         BookModels.Remove(bookModel);
     }
     else if (item is VideoGameModel videoGameModel)
     {
         VideoGameModels.Remove(videoGameModel);
     }
 }
コード例 #11
0
        public async Task <IActionResult> UploadBook(BookModels book)
        {
            if (ModelState.IsValid)
            {
                //check if FormFile is not null
                if (book.CoverPhotoFile != null)
                {
                    //function call to save image to mention file
                    //pass book path with filename to book model
                    book.BookCoverPhoto = await SaveImage("Images/Books/CoverPhoto/", book.CoverPhotoFile);;
                }
                if (book.BookGalleries != null)
                {
                    book.BookGallery = new List <BookGalleryModels>();
                    foreach (IFormFile file in book.BookGalleries)
                    {
                        BookGalleryModels Gallery = new BookGalleryModels()
                        {
                            PictureName = file.FileName,
                            URL         = await SaveImage("Images/Books/GalleryPhoto", file)
                        };
                        book.BookGallery.Add(Gallery);
                    }
                }
                if (book.BookPDF != null)
                {
                    string BookFile = "BookPDF/" + Guid.NewGuid().ToString() + "_" + book.BookPDF.FileName;
                    //create a url to save the book in the server
                    string serverFolder = Path.Combine(webHostEnvironment.WebRootPath, BookFile);
                    await book.BookPDF.CopyToAsync(new FileStream(serverFolder, FileMode.Create));

                    book.BookURL = "/" + BookFile;
                }
                long id = await bookRepository.AddNewBook(book);

                if (id > 0)
                {
                    return(RedirectToAction(nameof(UploadBook), new { isSuccess = true, BookID = (int)id }));
                }
            }

            //function call to get languages from database
            ViewBag.Languages = await LanguageDropDown();

            return(View());
        }
コード例 #12
0
        private BookModels GetBook(int bookId)
        {
            var model = new BookModels();

            using (var repo = new BookRepository())
            {
                model = repo.Details(bookId);
            }
            using (var repo_a = new AuthorRepository())
            {
                model.AuthorList = repo_a.FindAuthorsByBook(bookId).ToList();
            }
            foreach (var i in model.AuthorList)
            {
                model.SelectedAuthors.Add(i.Id);
            }
            return(model);
        }
コード例 #13
0
        public object Get(BookModels request)
        {
            if (!string.IsNullOrEmpty(request.AmazonUrl))
            {
                try
                {
                    var response = BookParser.GetBookDetails(request.AmazonUrl);
                    return(response);
                }
                catch
                {
                }
            }

            if (request.Id > 0)
            {
                var book = BookRepository.Find(request.Id);
                book.Description = HttpContext.Current.Server.HtmlDecode(book.Description);

                return(book);
            }

            var books = new List <BookModels>();

            if (request.CategoryId <= 0)
            {
                var userAuth   = this.GetSession();
                var userAuthId = userAuth.Id.To <int>();

                books = BookRepository.All().Where(a => a.UserId == userAuthId && (request.CategoryId <= 0 || a.CategoryId == request.CategoryId)).ToList();
            }
            else
            {
                books = BookRepository.All().Where(a => request.CategoryId <= 0 || a.CategoryId == request.CategoryId).ToList();
            }

            foreach (var book in books)
            {
                book.CategoryText = LookupRepository.Find(book.CategoryId).Name;
                book.Description  = HttpContext.Current.Server.HtmlDecode(book.Description);
            }

            return(books);
        }
コード例 #14
0
        public object Get(BookModels request)
        {
            if (!string.IsNullOrEmpty(request.AmazonUrl))
            {
                try
                {
                    var response = BookParser.GetBookDetails(request.AmazonUrl);
                    return response;
                }
                catch
                {
                }
            }

            if (request.Id > 0)
            {
                var book = BookRepository.Find(request.Id);
                book.Description = HttpContext.Current.Server.HtmlDecode(book.Description);

                return book;
            }

            var books = new List<BookModels>();
            if (request.CategoryId <= 0)
            {
                var userAuth = this.GetSession();
                var userAuthId = userAuth.Id.To<int>();

                books = BookRepository.All().Where(a => a.UserId == userAuthId && (request.CategoryId <= 0 || a.CategoryId == request.CategoryId)).ToList();
            }
            else
            {
                books = BookRepository.All().Where(a => request.CategoryId <= 0 || a.CategoryId == request.CategoryId).ToList();
            }

            foreach (var book in books)
            {
                book.CategoryText = LookupRepository.Find(book.CategoryId).Name;
                book.Description = HttpContext.Current.Server.HtmlDecode(book.Description);
            }

            return books;
        }
コード例 #15
0
        public async Task UpdateBook(BookModels _model)
        {
            // In this approach we are hitting database at only one time
            var books = new Books()
            {
                Id          = _model.Id,
                Title       = _model.Title,
                Description = _model.Description
            };

            _context.Books.Update(books);
            await _context.SaveChangesAsync();

            // In this approach we are hitting database at two times which is not good
            //var data = _context.Books.Find(_model.Id);
            //data.Title = _model.Title;
            //data.Description = _model.Description;
            //_context.Books.Update(data);
            //await _context.SaveChangesAsync();
        }
コード例 #16
0
        public object Put(BookModels request)
        {
            ValidationResult validations = new BookValidator().Validate(request);

            if (!validations.IsValid)
            {
                return(validations.Errors);
            }

            request.Description = HttpContext.Current.Server.HtmlEncode(request.Description);

            if (request.CategoryId <= 0)
            {
                request.CategoryId = LookupRepository.Insert(new CategoryModels
                {
                    Name      = request.CategoryText,
                    SortOrder = 0
                });
            }

            BookRepository.Update(request);

            return(request.Id);
        }
コード例 #17
0
        public async Task <IActionResult> UpdateBook([FromBody] BookModels _model)
        {
            await _bookRepository.UpdateBook(_model);

            return(Ok());
        }
コード例 #18
0
        // NOTE: The DevExpress POCO mechanism generates commands for all public methods without parameters or with a single parameter by convention.
        // Corresponding delegate command properties are created using the names of public methods with the suffix "Command".

        /// <summary>
        /// Creates a new dialog window that allows the user to add an item.
        /// </summary>
        /// <param name="itemType">The type of item is bound to the the tab the user is on (i.e adding from the movie tab creates a new movie).</param>
        public void AddItem(InventoryItemType itemType)
        {
            // Get the type of view model we are creating.
            Type viewModelType;

            switch (itemType)
            {
            case InventoryItemType.Book:
                viewModelType = typeof(BookModel);
                break;

            case InventoryItemType.Movie:
                viewModelType = typeof(MovieModel);
                break;

            case InventoryItemType.VideoGame:
                viewModelType = typeof(VideoGameModel);
                break;

            // Throw an exception if our item type does not match any of the models.
            default:
                throw new ArgumentOutOfRangeException();
            }

            // Resolve (create) the view model.
            if (!(App.ServiceProvider.GetService(viewModelType) is BaseInventoryModel viewModel))
            {
                return;
            }

            // Create a new button that adds the item.
            UICommand addItemCommand = new UICommand()
            {
                Caption   = "Add",
                IsDefault = true,

                // Only allow the user to add the item if there are no errors with the data entry.
                Command = new DelegateCommand(
                    () => { },
                    () => string.IsNullOrEmpty(viewModel.Error)
                    )
            };

            // Create a new button that cancels and closes the dialog window for adding an item.
            UICommand cancelCommand = new UICommand()
            {
                Caption  = "Cancel",
                IsCancel = true,
            };

            // Display the dialog window.
            UICommand result = AddOrModifyItemDialogService?.ShowDialog(
                dialogCommands: new[] { addItemCommand, cancelCommand },
                title: "Add a New Item",
                viewModel: viewModel
                );

            // Check if the user executed the add command (clicked the add button).
            if (result != addItemCommand)
            {
                return;
            }

            // Add the new model based on the type of item we are adding.
            switch (itemType)
            {
            case InventoryItemType.Book:
                BookModels.Add(viewModel as BookModel);
                break;

            case InventoryItemType.Movie:
                MovieModels.Add(viewModel as MovieModel);
                break;

            case InventoryItemType.VideoGame:
                VideoGameModels.Add(viewModel as VideoGameModel);
                break;

            // Throw an exception if our item type does not match any of the models.
            default:
                throw new ArgumentOutOfRangeException();
            }

            // Highlight the newly added item.
            FocusedItemModel = viewModel;
        }
コード例 #19
0
        public object Post(BookModels request)
        {
            ValidationResult validations = new BookValidator().Validate(request);

            if (!validations.IsValid)
            {
                request.ResponseResult.ResultStatus = ResultStatuses.Error;
                foreach (var item in validations.Errors)
                {
                    request.ResponseResult.Messages.Add(item.ErrorMessage);
                }

                return request;
            }

            if (request.InsertMode)
            {
                if (request.UserId <= 0)
                {
                    var userAuth = this.GetSession();
                    request.UserId = userAuth.Id.To<int>();
                }
            }

            request.Description = HttpContext.Current.Server.HtmlEncode(request.Description);
            if (request.Description.Length > 1500)
            {
                request.Description = request.Description.Substring(0, 1500);
            }

            if (request.CategoryId <= 0)
            {
                request.CategoryId = LookupRepository.Insert(new CategoryModels
                {
                    Name = request.CategoryText,
                    SortOrder = 0
                });
            }

            if (request.Id > 0)
            {
                BookRepository.Update(request);
            }
            else
            {
                BookRepository.Insert(request);
            }

            var liveMode = ServiceStack.Configuration.ConfigUtils.GetAppSetting("AppMode");
            if (request.InsertMode && liveMode.Equals("Live", StringComparison.InvariantCultureIgnoreCase))
            {
                // send a notification email
                EmailService.SendSmtpEmail(new EmailServiceModels
                {
                    Subject = "A New Book has been submitted and Needs your attention",
                    To = new List<string>() { "*****@*****.**", "*****@*****.**", "*****@*****.**" },
                    IsBodyHtml = false,
                    Body = string.Format("{0} has uploaded a book named {1}. You will need to upload the book to gumroad.", request.Author, request.Title),
                    Attachments = new List<string>() { string.Format("C:\\websites\\{0}", request.BookUrl) }
                });
            }

            return null;
        }
コード例 #20
0
        public static BookModels GetBookDetails(string url)
        {
            var book = new BookModels();

            book.AmazonUrl = url;

            var webGet  = new HtmlWeb();
            var htmlDoc = webGet.Load(url);

            htmlDoc.OptionFixNestedTags = true;

            // ParseErrors is an ArrayList containing any errors from the Load statement
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            {
                // Handle any parse errors as required
            }

            if (htmlDoc.DocumentNode != null)
            {
                HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

                if (bodyNode != null)
                {
                    var image = bodyNode.SelectSingleNode("//img[@id='main-image']");

                    if (image == null)
                    {
                        image = bodyNode.SelectSingleNode("//img[@id='imgBlkFront']");
                    }

                    if (image != null)
                    {
                        book.CoverUrl = image.Attributes["src"].Value;
                        book.CoverUrl = book.CoverUrl.Substring(0, book.CoverUrl.IndexOf("._")) + ".jpg";
                    }

                    var title = bodyNode.Descendants("span")
                                .Where(x => x.Id == "btAsinTitle")
                                .Select(s => s.InnerText);
                    book.Title = title.FirstOrDefault();

                    if (string.IsNullOrEmpty(book.Title))
                    {
                        title = bodyNode.Descendants("h1")
                                .Where(x => x.Id == "title")
                                .Select(s => s.InnerText);

                        book.Title = title.FirstOrDefault();
                    }

                    var price = bodyNode.SelectSingleNode("//b[@class='priceLarge']");

                    if (price != null)
                    {
                        book.Price = Convert.ToDecimal(price.InnerText.Trim().Replace("$", string.Empty).Replace("\n", string.Empty));
                    }

                    var description = bodyNode.SelectSingleNode("//div[@id='postBodyPS']")
                                      .InnerText;

                    book.Description = description;
                }
            }

            return(book);
        }
コード例 #21
0
        public object Post(BookModels request)
        {
            ValidationResult validations = new BookValidator().Validate(request);

            if (!validations.IsValid)
            {
                request.ResponseResult.ResultStatus = ResultStatuses.Error;
                foreach (var item in validations.Errors)
                {
                    request.ResponseResult.Messages.Add(item.ErrorMessage);
                }

                return(request);
            }

            if (request.InsertMode)
            {
                if (request.UserId <= 0)
                {
                    var userAuth = this.GetSession();
                    request.UserId = userAuth.Id.To <int>();
                }
            }

            request.Description = HttpContext.Current.Server.HtmlEncode(request.Description);
            if (request.Description.Length > 1500)
            {
                request.Description = request.Description.Substring(0, 1500);
            }

            if (request.CategoryId <= 0)
            {
                request.CategoryId = LookupRepository.Insert(new CategoryModels
                {
                    Name      = request.CategoryText,
                    SortOrder = 0
                });
            }

            if (request.Id > 0)
            {
                BookRepository.Update(request);
            }
            else
            {
                BookRepository.Insert(request);
            }

            var liveMode = ServiceStack.Configuration.ConfigUtils.GetAppSetting("AppMode");

            if (request.InsertMode && liveMode.Equals("Live", StringComparison.InvariantCultureIgnoreCase))
            {
                // send a notification email
                EmailService.SendSmtpEmail(new EmailServiceModels
                {
                    Subject = "A New Book has been submitted and Needs your attention",
                    To      = new List <string>()
                    {
                        "*****@*****.**", "*****@*****.**", "*****@*****.**"
                    },
                    IsBodyHtml  = false,
                    Body        = string.Format("{0} has uploaded a book named {1}. You will need to upload the book to gumroad.", request.Author, request.Title),
                    Attachments = new List <string>()
                    {
                        string.Format("C:\\websites\\{0}", request.BookUrl)
                    }
                });
            }

            return(null);
        }
コード例 #22
0
        public object Put(BookModels request)
        {
            ValidationResult validations = new BookValidator().Validate(request);

            if (!validations.IsValid)
            {
                return validations.Errors;
            }

            request.Description = HttpContext.Current.Server.HtmlEncode(request.Description);

            if (request.CategoryId <= 0)
            {
                request.CategoryId = LookupRepository.Insert(new CategoryModels
                {
                    Name = request.CategoryText,
                    SortOrder = 0
                });
            }

            BookRepository.Update(request);

            return request.Id;
        }
コード例 #23
0
        public static BookModels GetBookDetails(string url)
        {
            var book = new BookModels();
            book.AmazonUrl = url;

            var webGet = new HtmlWeb();
            var htmlDoc = webGet.Load(url);

            htmlDoc.OptionFixNestedTags = true;

            // ParseErrors is an ArrayList containing any errors from the Load statement
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            {
                // Handle any parse errors as required
            }

            if (htmlDoc.DocumentNode != null)
            {
                HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

                if (bodyNode != null)
                {
                    var image = bodyNode.SelectSingleNode("//img[@id='main-image']");

                    if (image == null)
                    {
                        image = bodyNode.SelectSingleNode("//img[@id='imgBlkFront']");
                    }

                    if (image != null)
                    {
                        book.CoverUrl = image.Attributes["src"].Value;
                        book.CoverUrl = book.CoverUrl.Substring(0, book.CoverUrl.IndexOf("._")) + ".jpg";
                    }

                    var title = bodyNode.Descendants("span")
                                        .Where(x=>x.Id == "btAsinTitle")
                                        .Select(s => s.InnerText);
                    book.Title = title.FirstOrDefault();

                    if (string.IsNullOrEmpty(book.Title))
                    {
                        title = bodyNode.Descendants("h1")
                                        .Where(x => x.Id == "title")
                                        .Select(s => s.InnerText);

                        book.Title = title.FirstOrDefault();
                    }

                    var price = bodyNode.SelectSingleNode("//b[@class='priceLarge']");

                    if (price != null)
                    {
                        book.Price = Convert.ToDecimal(price.InnerText.Trim().Replace("$", string.Empty).Replace("\n", string.Empty));
                    }

                    var description = bodyNode.SelectSingleNode("//div[@id='postBodyPS']")
                                              .InnerText;

                    book.Description = description;
                }
            }

            return book;
        }
コード例 #24
0
 public void Delete(BookModels request)
 {
     BookRepository.Delete((int)request.Id);
 }
コード例 #25
0
 public void Delete(BookModels request)
 {
     BookRepository.Delete((int)request.Id);
 }
コード例 #26
0
        /// <summary>
        /// Creates a new dialog window that allows the user to find an item.
        /// </summary>
        /// <param name="itemType">The type of item is bound to the the tab the user is on (i.e searching from the movie tab returns a movie).</param>
        public void FindItem(InventoryItemType itemType)
        {
            // Try to resolve FindItemViewModel.
            if (!(App.ServiceProvider.GetService(typeof(FindItemViewModel)) is FindItemViewModel viewModel))
            {
                return;
            }

            // Create a new button that finds the item.
            UICommand findItemCommand = new UICommand()
            {
                Caption   = "Search",
                IsDefault = true,

                // Only allow the user to find an item if there are no errors in the data entry.
                Command = new DelegateCommand(
                    () => { },
                    () => !string.IsNullOrWhiteSpace(viewModel.Title) && !string.IsNullOrWhiteSpace(viewModel.Platform)
                    )
            };

            // Create a new button that cancels and closes the dialog window for finding an item.
            UICommand cancelCommand = new UICommand()
            {
                Caption  = "Cancel",
                IsCancel = true,
            };

            // Display the dialog window.
            UICommand result = FindItemDialogService?.ShowDialog(
                dialogCommands: new[] { findItemCommand, cancelCommand },
                title: "Find an Item",
                viewModel: viewModel
                );

            // Check if the user executed the find command (clicked the find button).
            if (result != findItemCommand)
            {
                return;
            }

            // Switch based on the tab the user is on.
            switch (itemType)
            {
            case InventoryItemType.Book:
                // Return the first item that has the requested title and platform of the inventory item.
                FocusedItemModel = BookModels.FirstOrDefault(x =>
                                                             string.Equals(x.Title, viewModel.Title, StringComparison.InvariantCultureIgnoreCase) &&
                                                             string.Equals(x.Platform, viewModel.Platform, StringComparison.InvariantCultureIgnoreCase));
                break;

            case InventoryItemType.Movie:
                FocusedItemModel = MovieModels.FirstOrDefault(x =>
                                                              string.Equals(x.Title, viewModel.Title, StringComparison.InvariantCultureIgnoreCase) &&
                                                              string.Equals(x.Platform, viewModel.Platform, StringComparison.InvariantCultureIgnoreCase));
                break;

            case InventoryItemType.VideoGame:
                FocusedItemModel = VideoGameModels.FirstOrDefault(x =>
                                                                  string.Equals(x.Title, viewModel.Title, StringComparison.InvariantCultureIgnoreCase) &&
                                                                  string.Equals(x.Platform, viewModel.Platform, StringComparison.InvariantCultureIgnoreCase));
                break;

            // Throw an exception if our item type does not match any of the models.
            default:
                throw new ArgumentOutOfRangeException();
            }

            // If a model was not found, display a new message box indicating so to the user.
            if (FocusedItemModel == null)
            {
                MessageBoxService?.ShowMessage($"Could not find \"{viewModel.Title}\" on \"{viewModel.Platform}\"");
            }
        }
コード例 #27
0
 // 6) Change parameters and return type of UpdateBook()
 public void UpdateBook(BookModels bookModel)
 {
     // 7) use foreach to move through all books in list;
     // if book is find: remove it and add new from parameter
 }