/// <summary> /// Adds the bookData into the Books database, but only if it's not already present. /// If it's already /// </summary> /// <param name="bookData"></param> /// <returns>0=not added, 1=added. Technical is the count of the number added.</returns> public static int BookAdd(BookDataContext bookdb, BookData book, ExistHandling handling) { int retval = 0; NQueries++; lock (bookdb) { switch (handling) { case ExistHandling.IfNotExists: if (bookdb.Books.Find(book.BookId) == null) { bookdb.Books.Add(book); retval++; } break; case ExistHandling.CatalogOverrideFast: { var dbbook = bookdb.Books.Find(book.BookId); if (dbbook == null) { bookdb.Books.Add(book); retval++; } else // have to be smart. { if (dbbook.BookSource.StartsWith(BookData.BookSourceBookMarkFile)) { // The database was added to from a bookmark file. // For these books, the dbbook top-level data isn't correct but the user data is correct. // At the same time, the new book top-level data IS correct, but the user data is not correct. BookData.Merge(dbbook, book); retval++; } } } break; case ExistHandling.SmartCatalogOverride: { var dbbook = bookdb.Books.Find(book.BookId); if (dbbook == null) { bookdb.Books.Add(book); retval++; } else // have to be smart. { if (dbbook.BookSource.StartsWith(BookData.BookSourceBookMarkFile)) { // The database was added to from a bookmark file. // For these books, the dbbook top-level data isn't correct but the user data is correct. // At the same time, the new book top-level data IS correct, but the user data is not correct. BookData.Merge(dbbook, book); retval++; } else { // Grab the full data including the number of files dbbook = CommonQueries.BookGetFiles(bookdb, book.BookId); var mustReplace = book.Files.Count != dbbook.Files.Count; // In case the files don't match exactly.... if (!mustReplace) { //TODO: make faster? Or keep because it's needed functionality? mustReplace = !BookData.FilesMatch(book, dbbook); } if (mustReplace) { //FAIL: project gutenberg LOVES changing their URLs. If the old list doesn't match the // new list in number of files, then dump ALL the old values and replace them with the // new ones. // TODO: actually verify that the files match? // Can't use clear because it doesn't work: dbbook.Files.Clear(); // (Seriously: it doesn't work because Files doesn't implement it and will throw) for (int i = dbbook.Files.Count - 1; i >= 0; i--) { dbbook.Files.RemoveAt(i); } foreach (var file in book.Files) { if (file.Id != 0) { file.Id = 0; // if it's straight from the catalog, it should have no id } dbbook.Files.Add(file); } retval++; } } } } break; } return(retval); } }