Click here to Skip to main content
15,891,136 members
Articles / Desktop Programming / WPF

WPF Book Reader

Rate me:
Please Sign up or sign in to vote.
4.29/5 (16 votes)
10 May 2012GPL35 min read 110.9K   120  
A WPF book reader for cbz/cbr files
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace BookReader
{
	internal class Catalog
	{
		#region -----------------properties-----------------

		private string _bookPath = string.Empty;
		public string BookPath
		{
			get { return _bookPath; }
			set { _bookPath = value; }
		}
		private ObservableCollection<IBook> _Books = new ObservableCollection<IBook>();
		public ObservableCollection<IBook> Books
		{
		  get { return _Books; }
		  set { _Books = value; }
		}

		private bool _IsChanged = false;
		public bool IsChanged
		{
			get { return _IsChanged; }
			set { _IsChanged = value; }
		}

		#endregion

        #region -----------------refresh-----------------

        public void Refresh()
        {
            try
            {
                Thread t = new Thread(new ParameterizedThreadStart(RefreshThread));
                t.IsBackground = true;
                t.Priority = ThreadPriority.BelowNormal;
                t.Start(_bookPath);
            }
            catch (Exception err)
            {
				ExceptionManagement.Manage("Catalog:Refresh", err);
            }
        }

        internal void RefreshThread(object o)
        {
            try
            {
                //first, remove unfounded books
                List<IBook> temp = new List<IBook>();
                foreach (IBook book in this._Books)
                {
                    if (!File.Exists(book.FilePath))
                        temp.Add( book );
                }

                foreach (IBook book in temp)
                    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                    {
                        _Books.Remove(book);
                    });

                //then add the new ones
                ParseDirectoryRecursiveWithCheck(_bookPath);
            }
            catch (Exception err)
            {
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                {
                    ExceptionManagement.Manage("Catalog:RefreshThread", err);
                });
            }
        }

        #endregion

		public IBook Open(string book)
		{
			FileInfo file = new FileInfo(book);
			
			IBook bk = (IBook)new RarBook(file.FullName, true);
			bk.Size = file.Length;
			Books.Add(bk);
			this.IsChanged = true;

			return bk;
		}

        #region -----------------load/save-----------------

        public void Load(string path)
		{
			try
			{
				_bookPath = path;
				Load();
			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:LoadPath", err);
			}
		}

		private void Load()
		{
			try
			{
				string bin = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(".exe", ".bin");
				if (File.Exists(bin))
				{
					//load the book name and bookmark
					if (LoadBooks(bin))
					{
						bin = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(".exe", ".bin2");
						if (File.Exists(bin))
						{
							// load the cover images
							Thread t = new Thread(new ParameterizedThreadStart(LoadCovers));
							t.IsBackground = true;
							t.Priority = ThreadPriority.BelowNormal;
							t.Start(bin);
						}

						//then refresh the book
                        //Refresh();
					}
					else
						ParseDirectoryThread();
				}
				else //binary files does not exist, parse the directory
				{
					ParseDirectoryThread();
				}
			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:Load", err);
			}
		}

		public void Save()
		{
			try
			{
				if (IsChanged)
				{
					//remove the book without covers
					RemoveDirtyBooks();

					// save the books name and bookmarks
					string bin = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(".exe", ".bin");
					SaveBooks(bin);

					//save the covers
					bin = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(".exe", ".bin2");
					SaveCovers(bin);
				}
			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:Save", err);
			}
		}

		internal void RemoveDirtyBooks()
		{
			try
			{
				//remove books without covers
				List<IBook> temp = new List<IBook>();
				foreach (IBook book in this._Books)
				{
					if ( book.Cover == null )
						temp.Add(book);
				}

				foreach (IBook book in temp)
					_Books.Remove(book);

			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:RefreshThread", err);
			}
		}

		#endregion

		#region -----------------directory parsing-----------------

		internal void ParseDirectoryThread()
		{
			try
			{
				Books.Clear();

                Thread t = new Thread(new ParameterizedThreadStart(ParseDirectoryRecursive));
				t.IsBackground = true;
				t.Priority = ThreadPriority.BelowNormal;
				t.Start(_bookPath);
			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:ParseDirectoryThread", err);
			}
		}

		internal void ParseDirectoryRecursive(object path)
		{
			try
			{
				DirectoryInfo directory = new DirectoryInfo((string)path);
				if (!directory.Exists)
				{
                    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                    {
                        MessageBox.Show("Catalog path does not exist! Please check the options box");
                    });
					return;
				}
				foreach (FileInfo file in directory.GetFiles("*.*"))
				{
                    if (Properties.Settings.Default.BookFilter.Contains(file.Extension.ToUpper()))
					{
						Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)delegate
						{
                            IBook bk = (IBook)new RarBook(file.FullName, true);
							bk.Size = file.Length;
							Books.Add(bk);
							this.IsChanged = true;
						});
					}
				}
				foreach (DirectoryInfo dir in directory.GetDirectories("*", SearchOption.TopDirectoryOnly))
				{
					ParseDirectoryRecursive(dir.FullName);
				}
			}
			catch (Exception err)
			{
				Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
				{
					ExceptionManagement.Manage("Catalog:ParseDirectoryRecursive", err);
				});
				return;
			}

			return;
		}

        internal void ParseDirectoryRecursiveWithCheck(object path)
        {
            try
            {
                DirectoryInfo directory = new DirectoryInfo((string)path);
                if (!directory.Exists)
                {
                    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                    {
                        MessageBox.Show("Catalog path does not exist! Please check the options box");
                    });
                    return;
                }
                foreach (FileInfo file in directory.GetFiles("*.*"))
                {
                    if (Properties.Settings.Default.BookFilter.Contains(file.Extension.ToUpper()))
                    {
                        if( !BookExist( file.FullName ) )
                            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)delegate
                            {
                                IBook bk = (IBook)new RarBook(file.FullName, true);
                                bk.Size = file.Length;
                                Books.Add(bk);
                                this.IsChanged = true;
                            });
                    }
                }
                foreach (DirectoryInfo dir in directory.GetDirectories("*", SearchOption.TopDirectoryOnly))
                {
					ParseDirectoryRecursiveWithCheck(dir.FullName);
                }
            }
            catch (Exception err)
            {
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                {
					ExceptionManagement.Manage("Catalog:ParseDirectoryRecursiveWithCheck", err);
                });
                return;
            }

            return;
        }

        internal bool BookExist(string filepath)
        {
            foreach (IBook bk in _Books)
            {
                if (bk.FilePath == filepath)
                    return true;
            }
            return false;
        }
		#endregion

		#region -----------------load/save books collection-----------------

		private bool LoadBooks(string fileName)
		{
			bool result = true;

			IFormatter formatter = new BinaryFormatter();
			Stream stream = new FileStream(fileName,
				FileMode.Open,
				FileAccess.Read,
				FileShare.None);

			try
			{
				//the catalog path
				string booksFrom = (string)formatter.Deserialize(stream);

				//not on the same folder, restart from null
				if (this._bookPath != booksFrom || !Directory.Exists(this._bookPath))
				{
					this._Books = new ObservableCollection<IBook>();
					result = false;
				}
				else
				{
					//the book count
					int count = (int)formatter.Deserialize(stream);

					for ( int i = 0; i < count; i++ )
					{
						//each file path
						string filePath = (string)formatter.Deserialize(stream);
						long size = (long)formatter.Deserialize(stream);
						int nbPages = (int)formatter.Deserialize(stream);
						string bookmark = (string)formatter.Deserialize(stream);
                        bool isread= (bool)formatter.Deserialize(stream);
						FileInfo file = new FileInfo( filePath );
						if( file.Exists )
						{
							IBook bk = null;

                            if (Properties.Settings.Default.BookFilter.Contains(file.Extension.ToUpper()))
                                bk = (IBook)new RarBook(file.FullName, false);

							bk.Bookmark = bookmark;
							bk.Size = size;
							bk.NbPages = nbPages;
                            bk.IsRead = isread;

							this._Books.Add(bk); 
						}
					}
				}
			}
			catch( Exception err )
			{
				ExceptionManagement.Manage("Catalog:LoadBooks", err);
			}
			finally
			{
				stream.Close();
			}
			return result;
		}

		private void SaveBooks(string fileName)
		{
			IFormatter formatter = new BinaryFormatter();
			Stream stream = new FileStream(fileName,
				FileMode.Create,
				FileAccess.Write, FileShare.None);
			try
			{
				//the catalog path
				if (this._bookPath != null)
					formatter.Serialize(stream, this._bookPath);

				//the book count
				formatter.Serialize(stream, this._Books.Count);

				foreach (IBook book in this._Books)
				{
					//file path
					formatter.Serialize(stream, book.FilePath);
					//file size
					formatter.Serialize(stream, book.Size);
					//Nb pages
					formatter.Serialize(stream, book.NbPages);
					//Bookmark
					formatter.Serialize(stream, book.Bookmark);
                    //IsRead
                    formatter.Serialize(stream, book.IsRead);
                }
			}
			catch( Exception err )
			{
				ExceptionManagement.Manage("Catalog:SaveBooks", err);
			}
			finally
			{
				stream.Close();
			}
		}
		#endregion

		#region -----------------load/save covers-----------------

		public void LoadCovers(object fileName)
		{
			IFormatter formatter = new BinaryFormatter();
			Stream streamBin = new FileStream((string)fileName,
				FileMode.Open,
				FileAccess.Read,
				FileShare.None);

			try
			{
				//book count
				int count = (int)formatter.Deserialize(streamBin);

				for (int i = 0; i < count; i++)
				{
					string filePath = (string)formatter.Deserialize(streamBin);

                    //allways read the stream even if does not exist anymore
                    MemoryStream coverStream = (MemoryStream)formatter.Deserialize(streamBin);

					foreach (IBook book in this._Books)
					{
						if (book.FilePath == filePath)
						{
							MemoryStream stream2 = new MemoryStream();
							coverStream.WriteTo(stream2);
							coverStream.Flush();
							coverStream.Close();

							stream2.Position = 0;

							Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
							{
								BitmapImage myImage = new BitmapImage();
								myImage.BeginInit();
								myImage.StreamSource = stream2;
								myImage.DecodePixelWidth = 70;
								myImage.EndInit();

								book.Cover = myImage;
							});
							coverStream = null;
							stream2 = null;
						}
					}
				}
			}
			catch (Exception err)
			{
				Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
				{
					ExceptionManagement.Manage("Catalog:LoadCovers", err);
				});
			}
			finally
			{
				streamBin.Close();
			}
		}

		private void SaveCovers(string fileName)
		{
			IFormatter formatter = new BinaryFormatter();
			Stream stream = new FileStream(fileName,
				FileMode.Create,
				FileAccess.Write, FileShare.None);
			try
			{
				//book count
				formatter.Serialize(stream, this._Books.Count);

				foreach (IBook book in this._Books)
				{
					//each book path and cover
					formatter.Serialize(stream, book.FilePath);
					formatter.Serialize(stream, StreamToImage.GetStreamFromImage(book.Cover));
				}
			}
			catch (Exception err)
			{
				ExceptionManagement.Manage("Catalog:SaveCovers", err);
			}
			finally
			{
				stream.Close();
			}
		}
		
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Architect
France France
WPF and MVVM fan, I practice C # in all its forms from the beginning of the NET Framework without mentioning C ++ / MFC and other software packages such as databases, ASP, WCF, Web & Windows services, Application, and now Core and UWP.
In my wasted hours, I am guilty of having fathered C.B.R. and its cousins C.B.R. for WinRT and UWP on the Windows store.
But apart from that, I am a great handyman ... the house, a rocket stove to heat the jacuzzi and the last one: a wood oven for pizza, bread, and everything that goes inside

https://guillaumewaser.wordpress.com/
https://fouretcompagnie.wordpress.com/

Comments and Discussions