private async Task InitializeRecords()
        {
            var testAlbum = new AlbumRecord {
                IsShowcased = true, UserId = _testQuery.UserId.GetValueOrDefault()
            };
            var testBook = new BookRecord {
                IsShowcased = true, UserId = _testQuery.UserId.GetValueOrDefault()
            };
            var testGame = new GameRecord {
                IsShowcased = true, UserId = _testQuery.UserId.GetValueOrDefault()
            };
            var testMovie = new MovieRecord {
                IsShowcased = true, UserId = _testQuery.UserId.GetValueOrDefault()
            };

            await _context.AlbumRecords.AddAsync(testAlbum);

            await _context.BookRecords.AddAsync(testBook);

            await _context.GameRecords.AddAsync(testGame);

            await _context.MovieRecords.AddAsync(testMovie);

            await _context.SaveChangesAsync();
        }
예제 #2
0
            public void Should_Add_Book_Record_ToDb()
            {
                // Arrange
                string pathToFile = @"С:\Users\Dakosia\source\repos\CSharp\KazTourApp\KazTourApp.DAL\LiteDb.db";
                var    booking    = new BookRecord
                                    (
                    1,
                    1,
                    2,
                    1600000,
                    new DateTime(2018, 08, 11),
                    new DateTime(2018, 08, 25)
                                    );

                BookStorage storage = new BookStorage();
                int         itemsCountBeforeInsert = storage.ReadAllBookings().Count;

                // Act
                storage.AddBooking(booking);

                // Assert
                Assert.IsTrue(File.Exists(pathToFile));

                int itemsCountAfterInsert = storage.ReadAllBookings().Count;

                Assert.IsTrue(itemsCountBeforeInsert == itemsCountAfterInsert - 1);
            }
예제 #3
0
        public async Task <IHttpActionResult> PutBookRecord(Guid id, BookRecord bookRecord)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != bookRecord.RecordId)
            {
                return(BadRequest());
            }

            db.Entry(bookRecord).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookRecordExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #4
0
 public MutableView(ArrayBuffer <T> typedBuffer, TypedHandle <T> handle)
 {
     _manager    = typedBuffer;
     Array       = _manager.Raw;
     Record      = _manager.Book.RawArray[handle];
     this.Handle = handle;
 }
예제 #5
0
 public void UpdateBooking(int id, BookRecord record)
 {
     using (var db = new LiteDatabase(@"С:\Users\Dakosia\source\repos\CSharp\KazTourApp\KazTourApp.DAL\LiteDb.db"))
     {
         var bookings = db.GetCollection <BookRecord>("bookings");
         bookings.Update(id, record);
     }
 }
예제 #6
0
 public void AddClient(BookRecord record)
 {
     using (var db = new LiteDatabase(@"C:\Users\РаимбаевИ\Databases\LiteDb.db"))
     {
         var bookings = db.GetCollection <BookRecord>("bookings");
         bookings.Insert(record);
     }
 }
예제 #7
0
        static void Main(string[] args)
        {
            #region Class Approach
            BookClass b1 = new BookClass("Test Book", "Bob");
            BookClass b2 = new BookClass("Test Book 2", "Bob");

            var json = JsonSerializer.Serialize(b1);

            var equals = b1 == b2;

            Console.WriteLine($"is Equal?{equals}");
            Console.WriteLine(json);

            var b3 = JsonSerializer.Deserialize <BookClass>(json);

            var secondEquals = b3 == b1;

            Console.WriteLine($"is second Equal?{secondEquals}");

            (string bookName, string authorName) = b1;

            #endregion

            #region Record Approach

            var b4 = new BookRecord("Test Book 3", "Bob");
            var b5 = new BookRecord("Test Book 4", "Bob");

            var json2 = JsonSerializer.Serialize(b4);

            Console.WriteLine(json2);

            var b6 = JsonSerializer.Deserialize <BookRecord>(json2);

            var seprateRecordEquality = b4 == b5; //False

            var recordEquality = b4 == b6;        //True

            var b7 = b4;

            b4.AuthorName = "Peter";

            var sameRecordChangeCheck = b7 == b4; //True


            b4 = b4 with {
                AuthorName = "Peter"
            };                                                   //Record immutability ! A New Record is

            (string authorNameTuple, string bookNameTuple) = b4; // Test Book 3 , Peter

            var immutabilityEquality = b6 == b4;                 //False

            Console.WriteLine(b4.ToString());                    // Test Book 3 , Peter

            #endregion
        }
    }
예제 #8
0
        private static BookModel ConverToBookModel(BookRecord record, IEnumerable <AuthorRecord> authors, IEnumerable <GenreRecord> genres)
        {
            var bookAuthors = authors.Where(record.Authors, a => i => a.Id == i)
                              .Cast(a => new AuthorModel(a.Id, a.FirstName, a.LastName));
            var bookGenres = genres.Where(record.Genres, g => i => g.Id == i)
                             .Cast(g => new GenreModel(g.Id, g.Genre));

            return(new BookModel(record.Id, record.Title, record.PublicationDate, bookAuthors, bookGenres));
        }
예제 #9
0
 /// <summary>
 /// Удаляет информацию о книжке из локального хранилица
 /// </summary>
 /// <param name="book">Книга</param>
 /// <returns>False если данной книжки небыло в хранилище, True если была.</returns>
 public bool DeleteBook(BookRecord book)
 {
     if (Books.Contains(book))
     {
         Books.Remove(book);
         return(true);
     }
     return(false);
 }
        public List <BookRecord> GetBooksNotBorrowedForWeeks(int weeks)
        {
            List <BookRecord> booksNotBorrowedForWeeks = new List <BookRecord>();

            try
            {
                XElement doc      = XElement.Load(_bookCatalogPath);
                var      allBooks = doc.Elements(ConstantsBookRepository.BOOK_OBJECT).ToList();

                if (allBooks != null)
                {
                    foreach (XElement book in allBooks)
                    {
                        BookRecord newBookRecord = null;

                        DateTime lastBorrow      = DateTime.MinValue;
                        string   lastBorrowValue = book.Element(ConstantsBookRepository.BOOK_LAST_BORROW).Value;
                        if (lastBorrowValue != "" && lastBorrowValue != "01.01.0001")
                        {
                            if (!DateTime.TryParse(lastBorrowValue, out lastBorrow))
                            {
                                continue;
                            }

                            if (DateTime.Now.Subtract(lastBorrow).Days <= weeks * 7)
                            {
                                continue;
                            }
                        }

                        newBookRecord = new BookRecord()
                        {
                            Book = new Book()
                            {
                                Title  = book.Element(ConstantsBookRepository.BOOK_TITLE).Value,
                                Author = book.Element(ConstantsBookRepository.BOOK_AUTHOR).Value,
                                ISBN   = book.Element(ConstantsBookRepository.BOOK_ISBN).Value
                            },
                            LastBorrowDate = lastBorrow,
                            LastBorrower   = new Borrower()
                            {
                                Name     = book.Element(ConstantsBookRepository.BORROWER_OBJECT).Element(ConstantsBookRepository.BORROWER_NAME).Value,
                                LastName = book.Element(ConstantsBookRepository.BORROWER_OBJECT).Element(ConstantsBookRepository.BORROWER_LAST_NAME).Value,
                            }
                        };

                        booksNotBorrowedForWeeks.Add(newBookRecord);
                    }
                }
            }
            catch (Exception)
            { }

            return(booksNotBorrowedForWeeks);
        }
예제 #11
0
        public List <BookRecord> GetBooksNotBorrowedForWeeks(int weeks)
        {
            List <BookRecord> booksNotBorrowedForWeeks = new List <BookRecord>();

            try
            {
                var allBooks = JsonConvert.DeserializeObject <List <Library> >(File.ReadAllText(_bookCatalogPath));

                if (allBooks.Count > 0)
                {
                    foreach (Library book in allBooks)
                    {
                        BookRecord newBookRecord = null;

                        DateTime lastBorrow      = DateTime.MinValue;
                        string   lastBorrowValue = book.LastBorrowDate;
                        if (lastBorrowValue != "" && lastBorrowValue != "01.01.0001")
                        {
                            if (!DateTime.TryParse(lastBorrowValue, out lastBorrow))
                            {
                                continue;
                            }

                            if (DateTime.Now.Subtract(lastBorrow).Days <= weeks * 7)
                            {
                                continue;
                            }
                        }

                        newBookRecord = new BookRecord()
                        {
                            Book = new Book()
                            {
                                Title  = book.Title,
                                Author = book.Author,
                                ISBN   = book.Isbn
                            },
                            LastBorrowDate = lastBorrow,
                            LastBorrower   = new Borrower()
                            {
                                Name     = book.LastBorrower.Name,
                                LastName = book.LastBorrower.Lastname,
                            }
                        };

                        booksNotBorrowedForWeeks.Add(newBookRecord);
                    }
                }
            }
            catch (Exception)
            { }

            return(booksNotBorrowedForWeeks);
        }
예제 #12
0
        public async Task <IHttpActionResult> GetBookRecord(Guid id)
        {
            BookRecord bookRecord = await db.BookRecords.FindAsync(id);

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

            return(Ok(bookRecord));
        }
예제 #13
0
 // Диалог открытия txt файла книжки
 private void OnFileOpen(object sender, EventArgs e)
 {
     if (openFileDialog.ShowDialog() == DialogResult.OK)
     {
         // Если эту книжку уже открывали, то нужно октыть ее с сохнененным смещением
         // для этого нужно получить запись для этой книжки из хранилища
         string     owner      = Username.IsEmpty() ? null : Username;
         BookRecord bookRecord = Storage.GetRecord(openFileDialog.FileName, owner);
         OpenBook(bookRecord);
     }
 }
예제 #14
0
        public async Task <IHttpActionResult> PostBookRecord(BookRecord bookRecord)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.BookRecords.Add(bookRecord);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = bookRecord.RecordId }, bookRecord));
        }
예제 #15
0
        public ActionResult Lend(BookRecord bookRecord)
        {
            var d1 = _memberService.GetById(bookRecord.MemberId);
            var d2 = _bookService.GetById(bookRecord.BookId);
            var d3 = _staffService.GetById(bookRecord.StaffId);

            bookRecord.MemberId = d1.Id;
            bookRecord.BookId   = d2.Id;
            bookRecord.StaffId  = d3.Id;
            _bookRecordService.Add(bookRecord);
            return(RedirectToAction("Index"));
        }
예제 #16
0
 /// <summary>
 /// Добавляет или обновляет информацию о книжке в локальном хранилище
 /// </summary>
 /// <param name="book">Книга</param>
 /// <returns>False если книжка уже была в хранилице, True - если небыло.</returns>
 public bool AddBook(BookRecord book)
 {
     if (Books.Contains(book))
     {
         Books.Remove(book);
         Books.Add(book);
         return(false);
     }
     else
     {
         Books.Add(book);
         return(true);
     }
 }
예제 #17
0
        public async Task <IHttpActionResult> DeleteBookRecord(Guid id)
        {
            BookRecord bookRecord = await db.BookRecords.FindAsync(id);

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

            db.BookRecords.Remove(bookRecord);
            await db.SaveChangesAsync();

            return(Ok(bookRecord));
        }
예제 #18
0
        public static void UseRecords()
        {
            var bookRec = new BookRecord("Atomic Habits", "James Clear", "978-0735211292", 320);

            //deconstruct
            var(title, author, _, _) = bookRec;

            var otherBookRec = new BookRecord("Atomic Habits", "James Clear", "978-0735211292", 320);

            Console.WriteLine(bookRec);
            Console.WriteLine(otherBookRec);
            Console.WriteLine(bookRec == otherBookRec);      // True, because values are the same
            Console.WriteLine(bookRec.Equals(otherBookRec)); // True, because values are the same
        }
예제 #19
0
 // Диалог библиотеки (список всех книг)
 private void OnLibraryDialog(object sender, EventArgs e)
 {
     using (LibraryForm libraryDialog = new LibraryForm(Storage, Config, Connection))
     {
         if (libraryDialog.ShowDialog() == DialogResult.OK)
         {
             // Открываем выбранную книгу
             BookRecord selectedBook = libraryDialog.SelectedBook;
             if (!IsBookOpend || selectedBook != book.BookRecord)
             {
                 OpenBook(selectedBook);
             }
         }
     }
 }
 public void ClearList()
 {
     BookRecord temp = new BookRecord();
     if (m_pHead != null) //makes sure the list isn't empty
     {
         temp = m_pHead;
         while (m_pHead != null) //Goes through the list until the end
         {
             temp = m_pHead;
             m_pHead = m_pHead.getNext(); //Sets the head to the next node
             temp = new BookRecord(); //removes the node
         }
     }
     temp = null;
 }
예제 #21
0
        public bool Book([FromBody] BookActionDto dto)
        {
            var dinner = _context.Dinners.Find(dto.DinnerID);

            if (dinner == null)
            {
                return(false);
            }
            if (dto.DinnerDate.Add(dinner.DinnerTime).AddHours(7) < DateTime.Now)
            {
                return(false);
            }
            var diner = _context.Diners.Find(dto.DinerID);

            if (diner == null)
            {
                return(false);
            }
            if (dto.UnBook)
            {
                BookRecord existRecord = _context.BookRecords.FirstOrDefault(p => p.DinerID == dto.DinerID && p.DinnerID == dto.DinnerID && p.DinnerDate == dto.DinnerDate.AddHours(8));
                if (existRecord != null)
                {
                    _context.BookRecords.Remove(existRecord);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                if (_context.BookRecords.Where(p => p.DinerID == dto.DinerID && p.DinnerID == dto.DinnerID && p.DinnerDate == dto.DinnerDate.AddHours(8)).Count() > 0)
                {
                    return(false);
                }
                BookRecord bookRecord = BookRecord.CreateNewBookRecord(dto.DinerID, dto.DinnerID, dto.DinnerDate.ToLocalTime().Date, GetUserID());
                this._context.BookRecords.Add(bookRecord);
            }
            if (this._context.SaveChanges() == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public bool RemoveBookFromCatalog(BookRecord bookToRemove)
        {
            try
            {
                XDocument doc = XDocument.Load(_bookCatalogPath);
                doc.Descendants(ConstantsBookRepository.BOOK_OBJECT)
                .FirstOrDefault(e => e.Element(ConstantsBookRepository.BOOK_ISBN).Value == bookToRemove.Book.ISBN).Remove();
                doc.Save(_bookCatalogPath);

                return(true);
            }
            catch (Exception)
            { }

            return(false);
        }
        private void ClearList(BookRecord rt)
	{
		BookRecord temp = new BookRecord();
		if (m_pRoot != null)//makes sure the list isn't empty
		{
			temp = m_pRoot;
			while (m_pRoot != null)//Goes through the list until the end
			{
				temp = m_pRoot;
				m_pRoot = m_pRoot.getLeft();//Sets the head to the next Node
				temp = new BookRecord();//removes the node
				m_pRoot = m_pRoot.getRight();
			}
		}
		temp = null;
	}
예제 #24
0
        // Выгрузка книги на сервер
        private void OnUpload(object sender, EventArgs e)
        {
            BookRecord book = SelectedBook;

            byte[] buffer = File.ReadAllBytes(SelectedBook.Path);

            IMessage message = MessageFactory.MakeUploadBookMessage(
                System.IO.Path.GetFileNameWithoutExtension(book.Path),
                buffer, Token);

            Connection.Send(message);

            // fix
            UpdateCheckBox(true, true);
            //statusLabel.Text = "Uploading...";
            //progressBar.Visible = true;
        }
        public BookListGetQueryHandlerTests()
        {
            _fixture = new Fixture();
            _fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            _context = InitializeDatabase();

            _bookRecords = _fixture.Create <IEnumerable <BookRecord> >();
            _testQuery   = new BookListGetQuery(69, 0, string.Empty, _fixture.Create <ApplicationUser>());
            _testRecord  = _fixture
                           .Build <BookRecord>()
                           .With(book => book.User, _testQuery.User)
                           .With(book => book.UserId, _testQuery.User.Id)
                           .Create();

            _handler = new BookListGetQueryHandler(_context);
        }
예제 #26
0
        public BookIncrementReadCountCommandHandlerTests()
        {
            _fixture = new Fixture();
            _fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            _context = InitializeDatabase();

            _testCommand = _fixture.Create <BookIncrementReadCountCommand>();
            _testRecord  = _fixture
                           .Build <BookRecord>()
                           .With(a => a.Id, _testCommand.BookId)
                           .With(a => a.UpdatedOn, DateTimeOffset.UtcNow)
                           .With(a => a.User, _testCommand.User)
                           .With(a => a.UserId, _testCommand.User.Id)
                           .Create();

            _handler = new BookIncrementReadCountCommandHandler(_context);
        }
예제 #27
0
        /// <summary>
        /// Возвращает запись о книжке
        /// </summary>
        /// <param name="path">Путь к книжке на диске</param>
        /// <param name="owner">Владелец книжки</param>
        public BookRecord GetRecord(string path, string owner = null)
        {
            BookRecord bookRecord = new BookRecord()
            {
                Path   = path,
                Offset = 0,
                Owner  = owner
            };

            if (Books.Contains(bookRecord))
            {
                return(Books[Books.IndexOf(bookRecord)]);
            }
            else
            {
                return(bookRecord);
            }
        }
예제 #28
0
        // Открывает книжку
        private void OpenBook(BookRecord bookRecord)
        {
            if (IsBookOpend)
            {
                book.Close();
            }

            book              = new Book(bookRecord, richTextBox.Width, richTextBox.Height);
            book.BookOpend   += OnBookOpend;
            book.BookClosing += OnBookClosing;
            book.Open();

            if (!Token.IsEmpty())
            {
                bookRecord.Owner = Username;
            }
            Storage.AddBook(bookRecord);
        }
예제 #29
0
        private BookRecord GetBookRecord()
        {
            BookRecord bookRecord = null;

            Console.WriteLine("Find book by:\n 1: Title and author\n 2: ISBN");
            Console.Write("Command: ");
            switch (Console.ReadLine().Trim())
            {
            case "1":
                Console.Write("Title: ");
                string title = Console.ReadLine().Trim();
                Console.Write("Author: ");
                string author = Console.ReadLine().Trim();


                if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(author))
                {
                    Console.WriteLine("Incorrect data provided. Try again.");
                    break;
                }

                bookRecord = _bookRepository.GetBook(title, author);
                break;

            case "2":
                Console.Write("ISBN: ");
                string isbn = Console.ReadLine().Trim();

                if (string.IsNullOrWhiteSpace(isbn))
                {
                    Console.WriteLine("Incorrect data provided. Try again.");
                    break;
                }

                bookRecord = _bookRepository.GetBook(isbn);
                break;

            default:
                Console.WriteLine("[Warning] The parameter was not recognized");
                break;
            }

            return(bookRecord);
        }
예제 #30
0
 private bool RecordInvalid(int counter, ImportResult <Book> result, BookRecord record)
 {
     if (string.IsNullOrWhiteSpace(record.AreaName))
     {
         AddError(result, $"[{counter}]: Area name is null or empty.");
         return(true);
     }
     if (string.IsNullOrWhiteSpace(record.CategoryName))
     {
         AddError(result, $"[{counter}]: Category name is null or empty.");
         return(true);
     }
     if (string.IsNullOrWhiteSpace(record.Title))
     {
         AddError(result, $"[{counter}]: Title is null or empty.");
         return(true);
     }
     return(false);
 }
        public bool BorrowBook(BookRecord bookToBorrow)
        {
            try
            {
                XDocument doc = XDocument.Load(_bookCatalogPath);

                doc.Descendants(ConstantsBookRepository.BOOK_OBJECT)
                .FirstOrDefault(e => e.Element(ConstantsBookRepository.BOOK_ISBN).Value == bookToBorrow.Book.ISBN)
                .SetElementValue(ConstantsBookRepository.BOOK_LAST_BORROW, DateTime.Now.ToShortDateString());

                doc.Save(_bookCatalogPath);

                return(true);
            }
            catch (Exception)
            { }

            return(false);
        }
        public BookRecord GetBook(string isbn)
        {
            BookRecord bookRecord = null;

            try
            {
                XElement doc        = XElement.Load(_bookCatalogPath);
                var      targetBook = doc.Elements(ConstantsBookRepository.BOOK_OBJECT)
                                      .FirstOrDefault(e => e.Element(ConstantsBookRepository.BOOK_ISBN).Value == isbn);

                if (targetBook != null)
                {
                    bookRecord = GetSpecificBook(targetBook);
                }
            }
            catch (Exception)
            { }

            return(bookRecord);
        }
        //The function searchByClassification searches
        //for a book by the given classification number
        //and prints the information.
        public void searchByClassification(int cl)
	{
		if (m_pHead == null) //Checks if there is anything in the list, prints message if list is empty
		{
			Console.Error.WriteLine("There are no contents in this list!");
			return;
		}
		
		BookRecord temp = new BookRecord();
		int tempCL; 
		int tracker = 0; //Tracks every book found
		
		temp = m_pHead;
		tempCL = temp.getClassification();
		
		//This for loop searches the list until it ends
		while (temp != null)
		{
			tempCL = temp.getClassification();
			if(tempCL == cl)//if the classification numbers match,
			{
				temp.printRecord(); //the information is printed
				tracker++;
			}
			temp = temp.getNext(); // iterate
		}
		if (tracker <= 0)
		{
			Console.WriteLine("No item(s) with that classification number!");
		}
	}
 //The function PrintAll() recursively prints
 //all book records stored in the binary tree
 //Only the system directly interacts with this function
 private void PrintAll(BookRecord rt)
 {
     if (rt != null)
     {
         PrintAll(rt.getLeft());
         rt.printRecord();
         PrintAll(rt.getRight());
     }
 }
        //The function searchByStockNumber searches the list for books
        //with the given stock number and prints their information.
        public BookRecord searchByStockNumber(long stockNum)
        {
            if (m_pHead == null)//Checks if there is anything in the list, prints message if list is empty
            {
                Console.Error.WriteLine("There are no contents in this list!");
            }

            BookRecord temp = new BookRecord();
            Boolean isFound = false;
            temp = m_pHead;

            //The function searches the list until it reaches the end
            while (temp != null)
            {
                if (stockNum == temp.getStockNum()) //The book information is printed if it's found
                {
                    isFound = true;
                    return temp;
                }
                temp = temp.getNext(); //Iterate
            }
            if (isFound == false) //If the target is not found, return null
            {
                return null;
            }
            //Function won't ever get here, this is to stop the warning that  "not all control paths return a value"
            return null;
        }
        private StreamReader m_InFile; //equilavent to "InputStreamReader" in java


        public Book_Inventory()
        {
            m_pHead = null;
        }
        //The function removeBook searches for the stock number
        //of a Book Record and removes that book from the list.
        public Boolean removeBook(long stockNum)
	{
		BookRecord temp = new BookRecord();
		BookRecord back = new BookRecord();
		
		if (m_pHead == null) //CHecks if there is anything in the list
		{
			return false;
		}
		
		temp = m_pHead;
		back = null;
		while((temp != null) && (stockNum != temp.getStockNum())) //The function moves down the list
		{
			back = temp;
			temp = temp.getNext();
		}
		
		//If the list has reached the end and no book is found, a message is printed
		if(temp == null)
		{
			Console.WriteLine("Book not Found.");
			return false;
		}
		else if (back == null) //If the book is at the head, head points to the next node and the book is removed
		{
			m_pHead = m_pHead.getNext();
			temp = null;
		}
		else //If the book is not at the head, the node before the target is set to the node after the target
		{
			back.setNext(temp.getNext());
			temp = null; //he target is deleted.
		}
		return true;
	}
        //The addBook Function adds a Book Record to the end of the list
        public Boolean addBook(BookRecord br)
        {
            BookRecord temp, back, newNode = br; //create clone instances of inputted book record
            long key = newNode.getStockNum(); //retrieves the stock number of the book record...will be used as a key for sorting
            newNode.setNext(null); //sets the next node to null

            //If the head of the list is empty (as in no contents on the linked list), the head is set to the book(newNode)
            if (m_pHead == null)
            {
                m_pHead = newNode;
            }
            else //If head exists, the function searches the list and sorts/arranges the node based on their stock number
            {
                temp = m_pHead;
                back = null;
                while ((temp !=null) && (temp.getStockNum() < key))
                {
                    back = temp;
                    temp = temp.getNext();
                }
                if (back == null)
                {
                    newNode.setNext(m_pHead);
                    m_pHead = newNode;
                }
                else
                {
                    back.setNext(newNode);
                    newNode.setNext(temp);
                }
            }
            return true;
        }
 //The function searchByStockNumber searches the list for books
 //with the given stock number and prints their information.
 public BookRecord searchByStockNumber(long stockNum)
 {
     if (m_pRoot == null) //Checks if there is anything in the tree, prints message if the tree is empty
     {
         Console.Error.WriteLine("There are no contents in this tree!");
     }
     BookRecord temp = new BookRecord();
     temp = m_pRoot;
     //The function searches the tree until it reaches the end
     while ((temp != null) && temp.getStockNum() != stockNum)
     {
         if (stockNum < temp.getStockNum())
         {
             //Search key comes before this node, send temp to left child
             temp = temp.getLeft();
         }
         else
         {
             //Search key comes after this node, send temp to right child
             temp = temp.getRight();
         }
     }
     if (temp == null) //If the target is not found, return null
     {
         return null;
     }
     else //Target found!
     {
         temp.setLeft(null); //Safety purposes, prevents m_pLeft from being exposed to end user
         temp.setRight(null); //Safety purposes, prevents m_pRight from being exposed to end user
         return temp;
     }
     //Function won't ever get here, this is to stop the warning that "not all control paths return a value"
     //return null;
 }
 //The function searchByCost recursively searches
 //for each book that falls within the given
 //price range.
 //If found, it prints out the book information
 //Only the system directly interacts with this function
 private void searchByCost(double min, double max, BookRecord rt)
 {
     if (rt != null)
     {
         //Checks to see if the cost of the book falls within $10 of the range (min & max).
         if ((rt.getCost() >= (min - 5)) && (rt.getCost() <= (max + 5)))
         {
             rt.printRecord();//If it does, the information is printed
         }
         searchByCost(min, max, rt.getLeft());
         searchByCost(min, max, rt.getRight());
     }
 }
 //The addBook function adds a Book Record to the end of the list
 public Boolean addBook(BookRecord br)
 {
     //Checks to see there is really anything on br
     if (br == null)
     {
         return false;
     }
     BookRecord temp, back = new BookRecord(); //Create BookRecord instances
     temp = m_pRoot;
     back = null;
     while (temp != null) //Loop till temp falls out of the tree
     {
         back = temp;
         if (br.getStockNum() < temp.getStockNum())
         {
             temp = temp.getLeft();
         }
         else
         {
             temp = temp.getRight();
         }
     }
     //Attach new node to the node that back points to
     if (back == null) //Attach as root node in a new tree
     {
         m_pRoot = br;
     }
     else
     {
         if (br.getStockNum() < back.getStockNum())
         {
             back.setLeft(br);
         }
         else
         {
             back.setRight(br);
         }
     }
     return true;
 }
        public static void Main(String[] args)
        {

            //Testing for instance creation
            Console.WriteLine("\nTesting the default constructor for BookRecord...");
            BookRecord book1 = new BookRecord();
            book1.printRecord();
            //setter tests
            Console.WriteLine("\nTesting the setter functions of BookRecord...");
            String lebook = "James Potter";
            book1.setName(lebook);
            book1.setClassification(150);
            book1.setCost(95);
            book1.setStockNum(13232);
            book1.setNumberInStock(5);
            book1.printRecord();
            String lebook2 = "Harry Potter";
            BookRecord book2 = new BookRecord(lebook2, 111, 2, 4.33);
            //getter tests
            Console.WriteLine("\nTesting the getter functions of BookRecord...");
            book2.printRecord();
            Console.WriteLine(book1.getName());
            Console.WriteLine(book1.getClassification());
            Console.WriteLine(book1.getCost());
            Console.WriteLine(book1.getNumberInStock());
            Console.WriteLine(book1.getStockNum());
            //static test
            Console.WriteLine("\nTesting static instances of BookRecord...");
            BookRecord book3 = new BookRecord();
            book3.printRecord();
            String lebook3 = "James Potter";
            book3.setName(lebook3);
            book3.setClassification(150);
            book3.setCost(95);
            book3.setStockNum(13232);
            book3.setNumberInStock(5);
            book3.printRecord();
            //Book Inventory testing!
            Console.WriteLine("\nBook Database testing begins here...");
            //Initializing some of the stubs/drivers
            Book_Database Store = new Book_Database();
            BookRecord Book1 = new BookRecord("The Great Gatsby!", 21245, 343, 19.45);
            BookRecord Book2 = new BookRecord("The Stranger", 456121, 2342, 20.55);
            BookRecord Book3 = new BookRecord("Harry Potter", 234215, 443, 49.99);
            BookRecord book = new BookRecord();
            //Testing read Inventory & printAll & getNextLine
            Console.WriteLine("\nTesting read database...");
            Store.read_Database("BookData.txt");
            Console.WriteLine("\nTesting printAll()");
            Store.PrintAll();
            //Testing addBook
            Console.WriteLine("\nTesting addBook, (& from BookRecord->setNext, getNext)...");
            Store.addBook(Book1);
            Store.addBook(Book3);
            Store.addBook(Book2);
            Store.PrintAll();
            //Testing removeBook
            Console.WriteLine("\nTesting the removeBook function....");
            Store.removeBook(456121);
            Store.removeBook(4561);
            Store.PrintAll();
            //Testing BookRecord *searchByStockNumber
            Console.WriteLine("\nTesting the BookRecord *searchByStockNumber function");
            Console.WriteLine("First one");
            book = Store.searchByStockNumber(234215);
            if (book == null)
            {
                Console.WriteLine("Nothing here bob");
            }
            else
            {
                book.printRecord();
            }
            Console.WriteLine("second one");
            book = Store.searchByStockNumber(156121);
            if (book == null)
            {
                Console.WriteLine("Sorry, nothing here bob");
            }
            else
            {
                book.printRecord();
            }
            //Testing searchByClassification
            Console.WriteLine("\nTesting the searchByClassification function");
            Store.searchByClassification(443);
            Store.searchByClassification(000);
            //Testing searchByCost
            Console.WriteLine("\nTesting the searchByCost function");
            Console.WriteLine("For 10.00 to 58.85");
            Store.searchByCost(10.00, 58.65);
            Console.WriteLine("For 20. 55 to 100");
            Store.searchByCost(20.55, 100);
            Console.WriteLine("For 100 to 1000");
            Store.searchByCost(100, 1000);
            //Testing ClearList
            Console.WriteLine("\nTesting the ClearList function");
            Store.ClearList();
            Console.WriteLine("list cleared \n");
            Store.PrintAll();
            //Re-Testing all search functions after list is cleared
            Console.WriteLine("Re-Testing all search functions after list is cleared");
            Console.WriteLine("Re-Testing searchByStockNumber");
            book = Store.searchByStockNumber(4567);
            book = Store.searchByStockNumber(156121);

            //Re-testing searchByClassification
            Console.WriteLine("\nRe-Testing searchByClassification");
            Store.searchByClassification(443);
            Store.searchByClassification(000);

            Console.WriteLine("\nRe-Testing searchByCost");
            Console.WriteLine("For 10.00 to 58.85");
            Store.searchByCost(10.00, 58.65);

            Console.WriteLine("For 20. 55 to 100");
            Store.searchByCost(20.55, 100);
            Console.WriteLine("For 100 to 1000");
            Store.searchByCost(100, 1000);

        }
 //The function printAll goes through
 //the list and prints off each book Record.
 public void printAll()
 {
     if (m_pHead == null) //Checks if there is anything in the list, prints message if list is empty
     {
         Console.Error.WriteLine("Nothing to print.There are no contents in this list!");
         return;
     }
     BookRecord temp = new BookRecord();
     temp = m_pHead;
     while (temp != null)//The while loop runs through the list until it ends
     {
         temp.printRecord();
         temp = temp.getNext();
     }
 }
 private void searchByClassification(int cl, BookRecord rt)
 {
     int tempCL;//Since BookRecord::getClassification() is a
     //pass by reference function, tempCL is used to
     //obtain the classification number of the book.
     if (rt != null)
     {
         tempCL = rt.getClassification();
         if (cl == tempCL)
         {
             rt.printRecord();
         }
         searchByClassification(cl, rt.getLeft());
         searchByClassification(cl, rt.getRight());
     }
 }
        //The function searchByCost searches
        //for each book that falls within the given
        //price range.
        public void searchByCost(double min, double max)
	{	
		BookRecord temp = new BookRecord();

		temp = m_pHead;
		int tracker = 0; //Tracks every book found
		
		if (m_pHead == null) //Checks if there is anything in the list, prints message if list is empty
		{
			Console.Error.WriteLine("There are no contents in this list!");
		}
			
		
		while ((temp != null)) //The list is searched till end
		{
			//Checks to see if the cost of the book falls within the range (min & max)
			if ((temp.getCost() >= min) && (temp.getCost() <= max))
			{
				temp.printRecord(); //If it does, the information is printed.
				tracker++;
			}
			temp = temp.getNext();
		}
		
		if (tracker <= 0) //If no book is found in that price range
		{
			Console.WriteLine("No item(s) found for this price range!");
		}
	}
        //The function getNumberInStock searches
        //for a specific book by its stock number.
        //If the book is found, its information is printed.
        public int getNumberInStock(long sn)
        {
            if (m_pHead == null) //Checks if there is anything in the list, prints message if list is empty
            {
                Console.Error.WriteLine("There are no contents in this list!");
            }

            BookRecord temp = new BookRecord();
            temp = m_pHead;

            //The function searches the list until it ends or the matching stock number is found
            while ((temp != null) && (sn != temp.getStockNum()))
            {
                temp = temp.getNext();
            }
            if (temp == null) //If the match isn't found, return 0
            {
                return 0;
            }
            else //If there is a match, the number in stock is printed
            {
                return temp.getNumberInStock();
            }
        }
 //Constructor
 public Book_Database()
 {
     m_pRoot = null;
 }
        //This function reads the file and sets each line to their appropriate value
        //Note, the file must be in the same folder as the working directory/project folder
        public Boolean readInventory(String filename)
        {
            String line = "";
            int numBooks;
            if (!File.Exists(filename))
            {
                //File.Exists() returns false if the file could not be found or
                //if for some other reason the open failed.
                Console.Error.WriteLine("Unable to open file {0} in the path {1} \nProgram terminating", filename, Path.GetFullPath(filename));
                return false;
            }
            if (!(filename.ToString().Contains("txt")))
            {
                Console.Error.WriteLine("Sorry but {0} does not have file extension of .txt", filename);
            }
            try
            {
                Fread = new FileStream(filename, FileMode.Open, FileAccess.Read);
                BufFread = new BufferedStream(Fread);
                m_InFile = new StreamReader(BufFread);
            }
            catch (FileNotFoundException)
            {
                Console.Error.WriteLine("Sorry but {0} is not found in {1}", filename, Path.GetFullPath(filename));
            }

            //Read number of books, should be the first number in the inventory file
            line = getNextLine(line);
            numBooks = Convert.ToInt32(line); //Converts the number of books to an integer value
            for (int i = 0; i < numBooks; i++)
            {
                //The first loop creates a new Book Record for each book in the file.
                //The nested for loop to each the five lines that create Book Record.
                //The if statements sort each line and set them to their appropriate values.
                //When the last line is reach, the book is added to the list.
                BookRecord Book = new BookRecord();
                int j = 1;
                while (j <= 5)
                {
                    line = getNextLine(line);

                    if (j == 1)
                    {
                        Book.setStockNum(Convert.ToInt64(line));
                    }
                    else if (j == 2)
                    {
                        Book.setName(Convert.ToString(line));
                    }
                    else if (j == 3)
                    {
                        Book.setClassification(Convert.ToInt32(line));
                    }
                    else if (j == 4)
                    {
                        Book.setCost(Convert.ToDouble(line));
                    }
                    else if (j == 5)
                    {
                        Book.setNumberInStock(Convert.ToInt16(line));
                        addBook(Book);
                    }
                    j++;
                }
            }
            return true;
        }
        //The function removeBook searches for the stock number
        //of a Book Record and removes that book from the list.
        public Boolean removeBook(long stockNum)
	{
		BookRecord back = new BookRecord();
		BookRecord temp = new BookRecord();
		BookRecord delParent = new BookRecord(); //delParent = parent of node to remove, delNode = node to remove
		BookRecord delNode = new BookRecord(); 
		String tempName = "";
		temp = m_pRoot;
		back = null;
		if (temp == null)//Case 1: Checks to see there is anything in the tree
		{
			return false;
		}
		//Finding the node to delete.
		while ((temp != null) && (stockNum != temp.getStockNum()))
		{
			back = temp; //makes back the parent of temp
			if (stockNum < temp.getStockNum())
			{
				temp = temp.getLeft(); //send temp to the next node to the left
			}
			else
			{
				temp = temp.getRight(); //send temp to the next node to the right
			}
		}
		//If tree has reached the end and no book is found, a message is printed
		if (temp == null) //System didnt find anything to remove
		{
			Console.WriteLine("Book Not Found. Nothing was removed.\n");
			return false;
		}
		else //Prepare for deletion
		{
			if (temp == m_pRoot)//If the book is at the root, set delNode to root and delParent to null
			{
				delNode = m_pRoot;
				delParent = null;
			}
			else //Node to remove comes after the root node
			{
				delNode = temp;
				delParent = back;
			}
		}
		//Case 2: Removing node with zero or one child on the left
		if (delNode.getRight() == null) //The delNode has no right child
		{
			if (delParent == null) //Removing the root
			{
				m_pRoot = delNode.getLeft(); //make the left child the new root
				delNode = null;
				return true;
			}
			else //Not at root, decide which side of delParent, delNode is on
			{
				if (delParent.getLeft() == delNode) //Node to delete is a left child
				{
					delParent.setLeft(delNode.getLeft());
				}
				else //Node to delete is a right child
				{
					delParent.setRight(delNode.getLeft());
				}
				delNode = null;
				return true;
			}
		}
		else //Case 3: Deleting node has at least one child on the right
		{
			if (delNode.getLeft() == null) //The delNode has no left child
			{
				if (delParent == null)//Deleting the root
				{
					m_pRoot = delNode.getRight(); //make the right child the new root
					delNode = null;
					return true;
				}
				else //Not at root, decide which side of delParent, delNode is on
				{
					if (delParent.getLeft() == delNode) //Node to remove is a left child
					{
						delParent.setLeft(delNode.getRight());
					}
					else //Node to remove is a right child
					{
						delParent.setRight(delNode.getRight());
					}
					delNode = null;
					return true;
				}
			}
			else //Case 4: Removing node with two children.
			{
				//Find the replacement value. Locate the node containing the largest value smaller
				//than the key of the node being deleted
				temp = delNode.getLeft();
				back = delNode;
				while (temp.getRight() != null)
				{
					back = temp;
					temp = temp.getRight();
				}
				//Copy the replacement values into the
				//node to be "removed"
				tempName = temp.getName();
				delNode.setName(tempName);
				delNode.setClassification(temp.getClassification());
				delNode.setCost(temp.getCost());
				delNode.setNumberInStock(temp.getNumberInStock());
				delNode.setStockNum(temp.getStockNum());

				//delNode = temp;
				//Remove the replacement node from the tree.
				if (back == delNode)
				{
					back.setLeft(temp.getLeft());
				}
				else
				{
					back.setRight(temp.getLeft());
				}
				temp = null;
				return true;
			}
		}
	}