Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

WPF Book Reader

, 10 May 2012
A WPF book reader for cbz/cbr files
BookReaderv1.zip
Dependencies
7z.dll
BookReaderv1_source.zip
BookReader
ClassDiagram.cd
Dependencies
7-zip.dll
7z.dll
ICSharpCode.SharpZipLib.dll
SevenZipSharp.dll
WPFToolkit.dll
Properties
app.manifest
Settings.settings
Reader
Catalog
Common
Images
RAR
ZIP
Resources
TheRedPushPin.png
XAML
BookReaderv2.zip
7z.dll
BookReaderv2_8.zip
Release
BookReader.application
BookReader.exe
BookReader.exe.manifest
Dependencies
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
BookReaderv2_8_source.zip
BookReader.csproj.user
BookReader.csproj.vspscc
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
app.manifest
Settings.settings
acroread.png
document.png
ecran.png
exit.png
FitHeight.png
FitWidth.png
info.png
open_folder.png
refresh.png
Search.png
Theme
TheRedPushPin.png
tools.png
BookReaderv2_source.zip
BookReader.csproj.user
ClassDiagram.cd
7-zip.dll
7z.dll
ICSharpCode.SharpZipLib.dll
SevenZipSharp.dll
WPFToolkit.dll
app.manifest
Settings.settings
TheRedPushPin.png
BookReaderv3_0.zip
BookReader.application
BookReader.exe
BookReader.exe.manifest
BookReader.vshost.exe
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
BookReaderv3_0_source.zip
BookReader.csproj.user
BookReader.csproj.vspscc
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
app.manifest
Settings.settings
acroread.png
book.ico
document.png
ecran.png
exit.png
FitHeight.png
FitWidth.png
info.png
open_folder.png
refresh.png
Search.png
TheRedPushPin.png
tools.png
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)

Share

About the Author

Guillaume Waser
Architect A.C.S.
France France
No Biography provided

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 10 May 2012
Article Copyright 2009 by Guillaume Waser
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid