コード例 #1
0
        public void Setup()
        {
            Console.WriteLine("Welcome to The Library");
            //Library.PrintBooks();
            Book whereTheSidewalkEnds = new Book("Where the Sidewalk Ends", "Shel Silverstein", 19.99m);
            Book mossFlower           = new Book("Mossflower", "Brian Jacques", 9.99m);
            Book theRoad = new Book("The Road", "Cormac McCarthy", 14.99m);
            Book theUniverseInaNutShell = new Book("The Universe in a Nutshell", "Stephen Hawking", 4.99m);

            Books.Add(whereTheSidewalkEnds);
            Books.Add(mossFlower);
            Books.Add(theRoad);
            Books.Add(theUniverseInaNutShell);

            Cart = new List <IBuyable>();
            Item plasmasword = new Item("Plasma Sword", 450.00m, 20);
            Book theodyssey  = new Book("The Odyssey", "Homer", 0.99m);

            Cart.Add(plasmasword);
            Cart.Add(theodyssey);

            foreach (IBuyable cartItem in Cart)
            {
                cartItem.Purchase();
            }
        }
コード例 #2
0
        public MainPageViewModel(IWebApi webApi)
        {
            _webApi = webApi;

            MoreCommand.Subscribe(async _ =>
            {
                foreach (var book in await GetData())
                {
                    Books.Add(book);
                }
            });

            PrevCommand.Subscribe(_ =>
            {
                if (Position.Value > 0)
                {
                    Position.Value--;
                }
            });

            NextCommand.Subscribe(_ =>
            {
                if (Position.Value < Books.Count - 1)
                {
                    Position.Value++;
                }
            });
        }
コード例 #3
0
        /// <summary>
        /// Constructor. Gain all books at startup.
        /// </summary>
        public BookListStorage()
        {
            try
            {
                using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.OpenOrCreate)))
                {
                    // пока не достигнут конец файла
                    // считываем каждое значение из файла
                    while (reader.PeekChar() > -1)
                    {
                        var book = new Book
                        {
                            Id            = reader.ReadInt32(),
                            ISBN          = reader.ReadString(),
                            Author        = reader.ReadString(),
                            Title         = reader.ReadString(),
                            Publisher     = reader.ReadString(),
                            YearPublished = DateTime.Parse(reader.ReadString()),
                            Pages         = reader.ReadInt32(),
                            Price         = reader.ReadDouble(),
                        };

                        Books.Add(book);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #4
0
        //Függvény, ami meghívódik, ha a MainPage lesz az aktív View
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            //A visszagomb letiltása, hiszen a főoldalról nem tudunk visszább menni
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Disabled;

            //Új service indítása, colletion-ök feltöltése
            var service = new GoTService();

            var books = await service.GetBooksAsync();

            foreach (var b in books)
            {
                Books.Add(b);
            }

            var characters = await service.GetCharactersAsync();

            foreach (var c in characters)
            {
                Characters.Add(c);
            }

            var houses = await service.GetHousesAsync();

            foreach (var h in houses)
            {
                Houses.Add(h);
            }

            await base.OnNavigatedToAsync(parameter, mode, state);
        }
コード例 #5
0
        public async void GetData(int pageIndex)
        {
            PageIndex = pageIndex;
            var url = SoduPageValue.GetRankListPage(pageIndex.ToString());

            var html = await GetHtmlData(url, true, true);

            var list = ListPageDataHelper.GetRankListFromHtml(html);

            if (list == null)
            {
                ToastHelper.ShowMessage("排行榜数据获取失败");
            }
            else
            {
                if (pageIndex == 1)
                {
                    Books.Clear();
                }

                foreach (var book in list)
                {
                    Books.Add(book);
                }
                Title = $"排行榜({PageIndex}/{PageCount})";
            }
        }
コード例 #6
0
        public TextManageViewModel(IRegionManager regionManager, IPublisherService publisherService,
                                   ITextService textService)
        {
            mRegionManager    = regionManager;
            mPublisherService = publisherService;
            mTextService      = textService;
            var books = mPublisherService.GetPublishersAndBooks();

            foreach (var p in books)
            {
                foreach (var b in p.Books)
                {
                    var book = new BookVm
                    {
                        Title     = b.Title,
                        Id        = b.Id,
                        Publisher = p.Title
                    };
                    Books.Add(book);
                }
            }
            var texts = mTextService.GetTexts();

            foreach (var text in texts)
            {
                var book = Books.FirstOrDefault(a => a.Id == text.BookId);
                book?.Texts.Add(new TextVm
                {
                    Id    = text.Id,
                    Title = text.Title
                });
            }
        }
コード例 #7
0
        public void ReturnBook(string selection)
        {
            Book selectedBook = ValidateBook(selection, CheckedOut);

            if (selectedBook == null)
            {
                bool selecting = true;
                while (selecting)
                {
                    Console.Clear();
                    System.Console.WriteLine("Invalid Selection");
                    System.Console.WriteLine("Which book would you like to return?");
                    PrintCheckedBooks();
                    selection    = Console.ReadLine();
                    selectedBook = ValidateBook(selection, CheckedOut);
                    if (selectedBook != null)
                    {
                        selecting = false;
                    }
                }
            }
            selectedBook.Available = true;
            CheckedOut.Remove(selectedBook);
            Books.Add(selectedBook);
            System.Console.WriteLine($"You have successfully returned {selectedBook.Title}");
        }
コード例 #8
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            var characterUrl = (string)parameter;
            var service      = new CharacterService();

            Character = await service.GetCharacterAsync(characterUrl);


            var bookService = new BookService();

            foreach (var item in character.books)
            {
                var book = await bookService.GetBookAsync(item);

                Books.Add(book);
            }

            foreach (var item in character.povBooks)
            {
                var povBook = await bookService.GetBookAsync(item);

                Books.Add(povBook);
            }
            await base.OnNavigatedToAsync(parameter, mode, state);
        }
コード例 #9
0
ファイル: MainViewModel.cs プロジェクト: Hajks/BookLoader
 public void AddNewBook()
 {
     if (NewBook.IsValid)
     {
         Books.Add(new Book(NewBook));
     }
 }
コード例 #10
0
        public void UpdateBookTitle(string bookId, string newTitle)
        {
            var book = Books.Single(a => a.BookId.Value == bookId);

            Books.Add(new BookRecord(book.BookId, book.BookAmount, new BookTitle(newTitle)));
            Books.Remove(book);
        }
コード例 #11
0
 // добавляем команду
 void AddBook(object obj)
 {
     //MessageBox.Show("Добавлена книга", "Внимание!", MessageBoxButton.OK);
     Books.Add(new Book {
         Author = "Автор", Title = "Новая книга"
     });
 }
コード例 #12
0
        private void OnNewContentCommandExecute()
        {
            BookClass bookClass = Books.FirstOrDefault(h => h.DateBook == Data);

            if (bookClass != null)
            {
                bookManager.Delete(bookClass);
                Books.Remove(bookClass);
                bookManager.Add(bookManager.Create(Headline, Content, Data, CategoryClassesList));
                bookManager.Save();
                Books.Clear();
                Books.Add(bookManager.Create(Headline, Content, Data, CategoryClassesList));
            }
            else
            {
                if (Content is null || Headline is null)
                {
                    return;
                }
                bookManager.Add(bookManager.Create(Headline, Content, Data, CategoryClassesList));
                bookManager.Save();
                Books.Clear();
                Books.Add(bookManager.Create(Headline, Content, Data, CategoryClassesList));
            }
        }
コード例 #13
0
        public async Task LoadFullData(string id = null)
        {
            author = id == null
                ? await _gr.GetAuthorInfo(author.Id)
                : await _gr.GetAuthorInfo(id);

            NotifyPropertyChanged("ImageUrl");
            NotifyPropertyChanged("Name");
            NotifyPropertyChanged("Url");
            NotifyPropertyChanged("Hometown");
            NotifyPropertyChanged("BornAt");
            NotifyPropertyChanged("DiedAt");
            NotifyPropertyChanged("Genre");
            NotifyPropertyChanged("Gender");
            NotifyPropertyChanged("Link");
            NotifyPropertyChanged("CreatedAt");
            NotifyPropertyChanged("About");
            NotifyPropertyChanged("Rating");
            NotifyPropertyChanged("Influences");
            NotifyPropertyChanged("WorksCount");

            var authorBooks = await _gr.GetAuthorBooks(author.Id);

            foreach (var book in authorBooks.Book)
            {
                Books.Add(new BookViewModel(book));
            }
            NotifyPropertyChanged("Books");
        }
コード例 #14
0
        public void SeedData()
        {
            Database.EnsureCreated();

            if (!Authors.Any() && !Books.Any())
            {
                var authors = new List <AuthorEntity>();
                for (var authorCnt = 0; authorCnt < 5; authorCnt++)
                {
                    authors.Add(new AuthorEntity {
                        FirstName = $"Firstname {authorCnt + 1}", LastName = $"Lastname {authorCnt + 1}"
                    });
                }
                ;

                Authors.AddRange(authors);
                SaveChanges();

                var books = new List <BookEntity>();
                for (var bookCnt = 0; bookCnt < 20; bookCnt++)
                {
                    Books.Add(new BookEntity {
                        Title = $"Book {bookCnt + 1}", AuthorId = authors[bookCnt % authors.Count].Id
                    });
                    SaveChanges();
                }
            }
        }
コード例 #15
0
        async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Books.Clear();
                var books = await App.Database.GetBooksAsync();

                foreach (var book in books)
                {
                    Books.Add(book);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
コード例 #16
0
ファイル: cLibrary.cs プロジェクト: Sunvenger/MyLibrary
        internal void AddBookToSnapshot(cBook newBook)
        {
            Books.Add(newBook);

            var overrides  = new XmlAttributeOverrides();
            var attributes = new XmlAttributes();

            attributes.XmlIgnore = true;
            string plainTextXml;

            newBook.Borrowed = new cBorrowed
            {
                FirstName = "",
                LastName  = "",
                From      = ""
            };
            using (var sw = new StringWriter())
            {
                var xs = new XmlSerializer(typeof(cLibrary), overrides);
                xs.Serialize(sw, this);
                plainTextXml = sw.ToString();
            }


            XmlDocument newDoc = new XmlDocument();

            newDoc.LoadXml(plainTextXml);
            LibraryProvider.StreamSnapshot          = new MemoryStream();
            LibraryProvider.StreamSnapshot.Position = 0;
            newDoc.Save(LibraryProvider.StreamSnapshot);
            LibraryProvider.StreamSnapshot.Position = 0;
        }
コード例 #17
0
        public ActionResult Edit(BookModel model)
        {
            if (ModelState.IsValid)
            {
                foreach (AuthorModel author in model.Authors.ToList())
                {
                    if (string.IsNullOrWhiteSpace(author.FirstName) && string.IsNullOrWhiteSpace(author.LastName))
                    {
                        model.Authors.Remove(author);
                    }
                }

                BookModel itemToEdit = Books.Find(x => x.Id == model.Id);

                if (model.Image == null)
                {
                    model.Image = itemToEdit.Image;
                }
                else
                {
                    Utils.SaveFile(model.Image);
                }

                Books.Remove(itemToEdit);
                Books.Add(model);

                return(PartialView("TableRow", model));
            }
            else
            {
                return(PartialView("Edit", model));
            }
        }
コード例 #18
0
ファイル: HomeViewModel.cs プロジェクト: ItayTur/Book-Store
 /// <summary>
 /// Populates the books observalbe collection.
 /// </summary>
 /// <param name="books">The collection from which the items are taken.</param>
 private void FillBooksObervableCollections(IEnumerable <BookModel> books)
 {
     foreach (var book in books)
     {
         Books.Add(book);
     }
 }
コード例 #19
0
        private async Task AddBook()
        {
            var file = await CrossFilePicker.Current.PickFile();

            if (file == null)
            {
                return;
            }
            if (file.FileName.Substring(Math.Max(0, file.FileName.Length - 4)) != ".pdf")
            {
                await _pageService.DisplayAlert("Wrong extension", "Select .pdf file", null, "OK");

                return;
            }

            var content = await GetTextFromPDFAsync(file.FilePath);

            var           path        = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), file.FileName);
            List <string> listContent = content.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToList();

            File.WriteAllLines(path, listContent);

            _newBook = new Book()
            {
                Name  = file.FileName.Remove(file.FileName.Length - 4, 4),
                Path  = path,
                First = 0,
                Last  = listContent.Count
            };

            Books.Add(_newBook);
            await _bookStore.AddBook(_newBook);
        }
コード例 #20
0
        public void Add()
        {
            Filter = string.Empty;

            var book = new Book
            {
                ISBN           = string.Empty,
                Name           = string.Empty,
                InDate         = DateTime.Now,
                Price          = 0d,
                Pinyin         = string.Empty,
                BuyFrom        = BuyFroms[0],
                Remark         = string.Empty,
                TotalCount     = 1,
                AvailableCount = 1,
                Publisher      = string.Empty,
                Author         = string.Empty,
            };

            long rowid  = _repo.Add(book);
            bool result = rowid > 0;

            Status = string.Format("新增{0}!", result ? "成功" : "失败");

            if (result)
            {
                Logger.DebugFormat("新增Book,Id={0}", book.Id);
                Books.Add(book);
                SelectedBook = Books.Last();
                SendMsg(new ItemChangedMsg <Book>(ActionMode.Add, book));
            }
        }
コード例 #21
0
 private void AddNewBook()
 {
     Books.Add(new Book()
     {
         Author = "Test1", Title = "Test1", Count = 5, SN = "ISBN-10: 0735667454", Year = DateTime.Now
     });
 }
コード例 #22
0
    public void ShowCart()
    {
        var y = 1;

        for (int i = 0; i < Cart.Count; i++)
        {
            var currentBook = Cart[i];

            System.Console.WriteLine(y++ + ". " + currentBook.Title);
        }

        System.Console.WriteLine("Enter book number to return book or 'l' to return to the Library");
        var returnBook = Console.ReadLine();

        if (returnBook.ToLower() == "l")
        {
            MainScreen();
            return;
        }

        System.Console.WriteLine(returnBook);
        var index = int.Parse(returnBook) - 1;
        var book  = Cart[index];

        Books.Add(book);
        System.Console.WriteLine("You just returned " + book.Title);
        Cart.RemoveAt(index);
        ShowCart();
    }
コード例 #23
0
        /// <summary>
        ///     Initializes a new instance of the MainViewModel class. Initializes DataFields
        /// </summary>
        public MainViewModel(IDataService <TEntity> dataService)
        {
            _book        = new TEntity();
            Books        = dataService.GetBooks();
            _index       = 0;
            _dataService = dataService;

            Add = new RelayCommand(() =>
            {
                var add = GetClone(_book);
                Books.Add(add);
                _dataService.AddBook(add);
            });
            Remove = new RelayCommand(() =>
            {
                if (_index < Books.Count && _index >= 0)
                {
                    _dataService.RemoveBook(Books[Index]);
                    Books.RemoveAt(Index);
                }
            });

            Modify = new RelayCommand(() =>
            {
                GetClone(Book, Books[Index]);
                _dataService.ModifyBook(Books[Index]);
            });
        }
コード例 #24
0
        public async Task InitAsync(StoreAccess storeAccess)
        {
            int tryCount = 0;

            Books.Clear();
            _storeAccess = storeAccess;
            try
            {
                try
                {
                    tryCount++;
                    BookShelf = await _bookShelfService.LoadBookShelfAsync(storeAccess);
                }catch (Exception ex)
                {
                    tryCount++;
                    await Task.Delay(1000).ConfigureAwait(false);

                    BookShelf = await _bookShelfService.LoadBookShelfAsync(storeAccess);
                }

                foreach (var bookReference in BookShelf.Content)
                {
                    var bookVM = await BookViewModel.CreateAsync(_bookService, _eventAggregator, bookReference);

                    Books.Add(bookVM);
                }
            }
            catch (NoBookShelfExistsException ex)
            {
                _eventAggregator.GetEvent <NoBookShelfExistsMessage>().Publish(new Tuple <StoreAccess, string>(storeAccess, ex.Message + " - " + ex.AccessGrant + " - " + ex.AdditionalError + " - " + ex.StoreKey + " - " + tryCount.ToString() + " - " + ex.StackTrace));
            }
        }
コード例 #25
0
 public void OnGet()
 {
     foreach (var item in BookService.Content)
     {
         Books.Add(item);
     }
 }
コード例 #26
0
        public void ReturnBook(BookId bookId, BookAmount amount)
        {
            var book = Books.First(a => a.BookId == bookId);

            if (book.BookAmount == amount)
            {
                Books.RemoveAll(a => a.BookId == bookId);
            }
            else if (book.BookAmount > amount)
            {
                Books.RemoveAll(a => a.BookId == bookId);
                Books.Add(new BookRecord(book.BookId, book.BookAmount - amount, book.Title));
            }
            else
            {
                throw new ArgumentException($"Cannot return book with title {book.Title.Value}. Amount to return is higher than {book.BookAmount.Amount}");
            }

            AddEvent(new BookRemovedFromLibraryRecord(bookId, amount.Amount, (LibraryRecordId)Id));

            if (ReturnDate < DateTime.UtcNow)
            {
                var oldFineValue = ReturnFine.Value;
                var daysBetweenTodayAndReturnDate = ((DateTime.UtcNow - ReturnDate)).Days;
                var newFineValue = daysBetweenTodayAndReturnDate * 10;
                ReturnFine = new ReturnFine(oldFineValue + newFineValue);
            }

            if (ReturnFine.Value == 0)
            {
                IsClosed = true;
            }
        }
コード例 #27
0
ファイル: Library.cs プロジェクト: Daria-Koshkina/Library
        public void AddBook(string name, string authorName, string genreName, int year, string annotation)
        {
            Book book = new Book(name, GetAuthor(authorName), GetGenre(genreName), year, annotation);

            Books.Add(book);
            booksDao.Save(Books);
        }
コード例 #28
0
        private void AddBook_Click(object sender, RoutedEventArgs e)
        {
            Reset_Click(sender, e);
            int count = Books.Count;

            if (count < (int)LibrarySize.max && count >= (int)LibrarySize.min)
            {
                try
                {
                    if (this.TitleTextBox.Text != null)
                    {
                        Book book = new Book();
                        book.Title           = this.TitleTextBox.Text;
                        book.Name            = this.NameTextBox.Text;
                        book.Surname         = this.SurnameTextBox.Text;
                        book.PublishingHouse = this.PublishingHouseTextBox.Text;
                        book.PublicationDate = int.Parse(this.PublicationDateTextBox.Text);
                        book.Genre           = this.GenreComboBox.Text;
                        Books.Add(book);
                    }
                }
                catch
                {
                    MessageBox.Show("Dodaj tytuł lub wpisz poprawnie datę!",
                                    "Uwaga", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
コード例 #29
0
ファイル: BooksViewModel.cs プロジェクト: orItach/BooksStore
        async Task ExecuteLoadBooksCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Books.Clear();
                var items = await DataStore.GetBooksAsync(true);

                foreach (var item in items)
                {
                    Books.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
コード例 #30
0
        public BookSeries AddBook(Book book)
        {
            ValidateBook(book);
            Books.Add(book);

            return(this);
        }
コード例 #31
0
ファイル: MainWindow.xaml.cs プロジェクト: powernick/CodeLib
        // Get entities of the books.
        private void LoadBooks()
        {
            _books = new Books();
            _localPath = Directory.GetCurrentDirectory();
            _localEntityPath = _localPath + "/Datas";
            _localImagePath = _localPath + "/Datas/Images/";
            DirectoryInfo info = new DirectoryInfo(_localEntityPath);

            // Check Dir info.
            if (!info.Exists)
            {
                info.Create();
            }

            String entityPath = info.FullName + "/books.xml";

            // If the entity file exist, get entity from xml file.
            if (File.Exists(entityPath))
            {
                using (FileStream stream = File.Open(entityPath, FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Books));
                    _books = serializer.Deserialize(stream) as Books;
                }
            }
            else
            {
                _books = new Books();
                _books.Add(new Book
                {
                    Title = "<New Book>",
                    ISBN = "0-000-00000-0"
                });
            }

            // Set correct image path for each book.
            foreach (Book book in _books)
            {
                if (!String.IsNullOrEmpty(book.Image))
                {
                    book.Image = book.Image.Replace("$(Booklist)", _localImagePath);
                }
            }
        }