internal static async Task UpdateTile(IDisposable CanvasDevice, BookItem Book, string TileId) { TileUpdater Updater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(TileId); Updater.EnableNotificationQueue(true); Updater.Clear(); StringResources stx = StringResources.Load("Message"); XmlDocument Template150 = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text01); Template150.GetElementsByTagName("text").First().AppendChild(Template150.CreateTextNode(stx.Str("NewContent"))); Updater.Update(new TileNotification(Template150)); XmlDocument Template71 = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare71x71Image); IXmlNode ImgSrc = Template71.GetElementsByTagName("image") .FirstOrDefault()?.Attributes .FirstOrDefault(x => x.NodeName == "src"); string SmallTile = await Image.LiveTileBadgeImage(CanvasDevice, Book, 150, 150, "\uEDAD"); if (!string.IsNullOrEmpty(SmallTile)) { ImgSrc.NodeValue = SmallTile; Updater.Update(new TileNotification(Template71)); } }
private void BookListBox_OnAction(object sender, BookItem item, ActionEvent e) { if (e == ActionEvent.CLICK) { ViewModel.Navigate(typeof(ReadPage), item, true); } }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { RingVisibility = Visibility.Visible; Task.Factory.StartNew(() => { DatabaseHelper.Open(); try { var reader = DatabaseHelper.Select <BookItem>("*", "ORDER BY Time DESC"); while (reader.Read()) { if (reader.HasRows) { var item = new BookItem(reader); Application.Current.Dispatcher.Invoke(() => { BooksList.Add(item); }); } } reader.Close(); } catch (Exception) { DatabaseHelper.Init(); } DatabaseHelper.Close(); RingVisibility = Visibility.Collapsed; }); }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { RingVisibility = Visibility.Visible; Task.Factory.StartNew(() => { DatabaseHelper.Open(); try { var reader = DatabaseHelper.Select<BookItem>("*", "ORDER BY Time DESC"); while (reader.Read()) { if (reader.HasRows) { var item = new BookItem(reader); Application.Current.Dispatcher.Invoke(() => { BooksList.Add(item); }); } } reader.Close(); } catch (Exception) { DatabaseHelper.Init(); } DatabaseHelper.Close(); RingVisibility = Visibility.Collapsed; }); }
public BookItemViewModel GetBookViewModel(BookItem book, ApplicationDbContext db) { BookItemViewModel bookView = new BookItemViewModel(); bookView.ID = book.BookItemID; bookView.Title = book.Title; bookView.ISBN = book.ISBN; bookView.Publisher = book.Publisher; bookView.ReleaseDate = book.ReleaseDate; bookView.Descryption = book.Descryption; if (book.Category != null) { bookView.Category = db.Categories.Single(c => c.CategoryID == book.Category.CategoryID); bookView.CategoryID = book.Category.CategoryID; } bookView.Authors = db.Authors.Where(a => a.AuthorGroups.Any(g => g.BookItem.BookItemID == book.BookItemID)).ToList(); bookView.Labels = db.Labels.Where(a => a.LabelGroups.Any(g => g.BookItem.BookItemID == book.BookItemID)).ToList(); bookView.Number = book.Number; bookView.SelectedLabels = bookView.Labels.Select(x => x.LabelID).ToList(); bookView.SelectedAuthors = bookView.Authors.Select(x => x.AuthorID).ToList(); bookView.AvailableNumber = book.Number - db.Orders.Count(o => o.BookItemID == book.BookItemID && o.Returned); return(bookView); }
public BookCoverViewModel(BookItem item) { Title = item.Title; Id = item.Id; CoverImageUri = item.CoverImageUri; ItemType = item.ItemType; }
public ActionResult BorrowBook(int?IdBook) { if (IdBook == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var book = db.Books.Find(IdBook); if (book == null) { return(HttpNotFound()); } var userId = User.Identity.GetUserId(); var bookItem = new BookItem { BookId = book.Id, Book = book, BookingAccountId = db.BookingAccounts.Where(ba => ba.ApplicationUserId == userId).First().Id, BookingAccount = db.BookingAccounts.Where(ba => ba.ApplicationUserId == userId).First(), DateOfReceip = DateTime.Now.Date, DateOfReturn = DateTime.Now.Date, }; return(View(bookItem)); }
private async void SetTemplate( BookItem b ) { ReviewsSection = new ReviewsSection( b ); // Let's try the async method this time await ReviewsSection.Load(); DataContext = ReviewsSection; }
public void InfoView(BookItem Book) { var j = Dispatcher.RunIdleAsync((x) => { ControlFrame.Instance.NavigateTo(PageId.BOOK_INFO_VIEW, () => new BookInfoView(Book)); }); }
private void M0005_ReadingHistory() { XRegistry XReg = new XRegistry("<n/>", FileLinks.ROOT_SETTING + "ReadingHistory.xml"); XParameter[] XParams = XReg.Parameters(); foreach (XParameter XParam in XParams) { string Id = XParam.Id; string Name = XParam.GetValue("name"); string Date = XParam.GetValue("date"); if (int.TryParse(Id, out int aid)) { BookItem Bk = X.Instance <BookItem>(XProto.BookItemEx, Id); Bk.Title = Name; if (DateTime.TryParse(Date, out DateTime dt)) { Bk.Entry.LastAccess = dt; } } } Shared.BooksDb.SaveChanges(); }
public boolean checkoutBookItem(BookItem bookItem) { if (this.getTotalBooksCheckedOut() >= Constants.MAX_BOOKS_ISSUED_TO_A_USER) { ShowError("The user has already checked-out maximum number of books"); return(false); } BookReservation bookReservation = BookReservation.fetchReservationDetails(bookItem.getBarcode()); if (bookReservation != null && bookReservation.getMemberId() != this.getId()) { // book item has a pending reservation from another user ShowError("This book is reserved by another member"); return(false); } else if (bookReservation != null) { // book item has a pending reservation from the give member, update it bookReservation.updateStatus(ReservationStatus.COMPLETED); } if (!bookItem.checkout(this.getId())) { return(false); } this.incrementTotalBooksCheckedout(); return(true); }
public async Task UpdateBookAsync_WhenUpdatesInStorage_ReturnsSuccess() { //Arrange var expectedBookId = Guid.NewGuid().ToString(); var expectedBookModel = new BookModel { BookId = expectedBookId, AuthorId = "1", Name = "1" }; //strict matching to make sure mapping is done correctly BookItem updatedBookItem = null; _booksRepositoryMock.Setup(x => x.UpdateAsync(It.IsAny <BookItem>())) .Callback <BookItem>(x => updatedBookItem = x) .ReturnsAsync(Result.Success <Unit, Error>(Unit.Instance)); //Act var result = await _sut.UpdateBookAsync(expectedBookId, expectedBookModel); //Assert result.IsSuccess.Should().BeTrue(); updatedBookItem.Should().BeEquivalentTo(expectedBookModel, config => config.Excluding(bi => bi.BookId)); updatedBookItem.BookId.Should().BeEquivalentTo(expectedBookId); }
public BookCoverViewModel(BookItem item) { Title = item.Title; Id = item.Id; CoverImageUri = item.CoverImageUri; ItemType = item.ItemType; }
void UseBook(ItemInfo MItemInfo) { BookItem book = MItemInfo.item as BookItem; switch (book.BookType) { case BookType.Building: if (TryLoseItem_Boolean(MItemInfo, 1) && BuildingManager.Instance.Learn(book.BuildingToLearn)) { LoseItem(MItemInfo, 1); BuildingManager.Instance.Init(); } break; case BookType.Making: if (TryLoseItem_Boolean(MItemInfo, 1) && MakingManager.Instance.Learn(book.ItemToLearn)) { LoseItem(MItemInfo, 1); MakingManager.Instance.Init(); } break; case BookType.Skill: default: break; } }
public static BookItem CeateNew(int _index, GameObject gameParent, bool isFilt) { Object prefab = null; if (prefab == null) { prefab = exResources.GetResource(ResourceType.GUI, "SpiritAnimal/AnimalItem"); } if (prefab == null) { GameSys.LogError("找不到AnimalItem预制"); return(null); } GameObject obj = Instantiate(prefab) as GameObject; obj.transform.parent = gameParent.transform; if (isFilt) { obj.transform.localPosition = new Vector3((_index % 2) * 120, -(_index / 2) * 168); } else { obj.transform.localPosition = new Vector3(90 * _index, 0); } obj.transform.localScale = Vector3.one; BookItem itemUI = obj.GetComponent <BookItem>(); if (itemUI == null) { GameSys.LogError("预制上找不到组件:<BookItem>"); return(null); } return(itemUI); }
public Task CreateBookItemAsync(BookItem bookItem) { bookItem.Id = Guid.NewGuid().ToString(); context.BookItems.Add(bookItem); return(context.SaveChangesAsync()); }
private void OnComplete(BookItem b) { if (CompleteHandler != null) { Worker.UIInvoke(() => { CompleteHandler(b); }); } }
public async Task <ActionResult <BookItem> > PostBookItem(BookItem book) { _context.BookItems.Add(book); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetBookItem), new { id = book.BookItemId }, book)); }
public double predictRating(BookUser user, BookItem item) { switch (type) { case RecommendationType.USER_BASED: return(estimateUserBasedRating(user, item)); case RecommendationType.IMPROVED_USER_BASED: return(estimateUserBasedRating(user, item)); case RecommendationType.ITEM_BASED: return(estimateItemBasedRating(user, item)); case RecommendationType.ITEM_PENALTY_BASED: return(estimateItemBasedRating(user, item)); case RecommendationType.USER_CONTENT_BASED: throw new Exception("Not valid for current similarity type:" + type); case RecommendationType.USER_ITEM_CONTENT_BASED: return(MAX_RATING * similarityMatrix.getValue(user.UserId, item.getId())); default: throw new Exception("Unknown recommendation type:" + type); } }
public BookEditViewModel GetBookEditViewModel(BookItem book, ApplicationDbContext db) { BookEditViewModel bookView = new BookEditViewModel(); var item = GetBookViewModel(book, db); bookView.BookItemViewModel = item; foreach (var file in book.Attachments) { switch (file.FileType) { case FileType.Cover: bookView.Cover = file; break; case FileType.TableOfContents: bookView.Table = file; break; case FileType.Attachment: bookView.OldFiles.Add(file); break; } } return(bookView); }
public async Task <bool> UpsertBook(BookItem bookItem) { try { var existingBook = await GetBookData(bookItem.Id); if (existingBook != null) { existingBook = bookItem; await _bookItemsDbContext.SaveChangesAsync(); } else { _bookItemsDbContext.BookItems.Add(bookItem); await _bookItemsDbContext.SaveChangesAsync(); //_logger.LogInformation("New DB record created from the data resources file"); } return(true); } catch (Exception exception) { //_logger.Err("DB records updated from the data resources file"); return(false); } }
private async void MessageBus_OnDelivery(Message Mesg) { // Handles secondary tile launch on App opened switch (Mesg.Content) { case AppKeys.SYS_2ND_TILE_LAUNCH: case AppKeys.SYS_FILE_LAUNCH: if (Navigating) { ActionBlocked(); return; } BookItem Book = null; if (Mesg.Payload is string) { Book = await ItemProcessor.GetBookFromTileCmd(( string )Mesg.Payload); } else if (ItemProcessor.RequestOpenXRBK(Mesg.Payload, out var ISF)) { Book = await _BgTaskContext.RunAsync(ItemProcessor.OpenXRBK, ISF); } if (Book != null) { NavigateTo(PageId.MONO_REDIRECTOR, () => new MonoRedirector(), P => (( MonoRedirector )P).InfoView(Book)); } break; } }
/// <summary> /// 著者の登録 /// </summary> /// <param name="data">データ</param> private int InsertAuthor(BookItem data) { var cd = 0; var author = this._dbContext.Author.FirstOrDefault(x => x.AuthorName == data.Author); if (author == null) { cd = this._dbContext.Author.Max(x => x.AuthorCd) + 1; var entity = new Author { AuthorCd = cd, AuthorName = data.Author, }; this._dbContext.Author.Add(entity); } else { cd = author.AuthorCd; } return(cd); }
/// <summary> /// 加入购物车 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Linkbtn_Shoppingcart_Click(object sender, EventArgs e) { if (Session["User"] != null) { Customer currentUser = (Customer)Session["User"]; //读取当前用户信息 BookItem bookItem = new BookItem(book); //创建一个bookItem //下面的逻辑有点乱 //可以只通过读取User信息就好了 if (Session["ShoppingCart"] != null) { ShoppingCart shoppingCart = (ShoppingCart)Session["ShoppingCart"]; shoppingCart.AddBookItemToShoppingCart(bookItem); //将bookItem添加到shoppingCart中 Session["ShoppingCart"] = shoppingCart; //保存购物车 } else { currentUser.ShoppingCart.AddBookItemToShoppingCart(bookItem); //将bookItem添加到shoppingCart中 Session["ShoppingCart"] = currentUser.ShoppingCart; //保存购物车 } //提醒用户已经添加到购物车 Response.Write("<script>alert('成功添加到购物车中!')</script>"); } else { Response.Write("<script>alert('登陆失效,请重新登陆!')</script>"); } }
/// <summary> /// 出版社の登録 /// </summary> /// <param name="data">データ</param> private int InsertPublisher(BookItem data) { var cd = 0; var publisher = this._dbContext.Publisher.FirstOrDefault(x => x.PublisherName == data.Publisher); if (publisher == null) { cd = this._dbContext.Publisher.Max(x => x.PublisherCd) + 1; var entity = new Publisher { PublisherCd = cd, PublisherName = data.Publisher, }; this._dbContext.Publisher.Add(entity); } else { cd = publisher.PublisherCd; } return(cd); }
private static bool SaveCarinDB(string userID, BookItem book) { bool result = false; if (userID != "") { string sqlText = @"INSERT INTO shoppingCart ( userId, bookId,qty ) VALUES( @parameterUserId, @parameterBookId, @parameterQTY );"; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(sqlText)) { cmd.Parameters.Add(new SqlParameter("@parameterUserId", userID)); cmd.Parameters.Add(new SqlParameter("@parameterBookId", book.ISBN)); cmd.Parameters.Add(new SqlParameter("@parameterQTY", book.quantity)); cmd.Connection = con; con.Open(); Int32 count = Convert.ToInt32(cmd.ExecuteScalar()); result = (count > 0); } con.Close(); } } return(result); }
/// <summary> /// 分類の登録 /// </summary> /// <param name="data">データ</param> private int InsertClass(BookItem data) { var cd = 0; var classData = this._dbContext.Class.FirstOrDefault(x => x.ClassName == data.Class); if (classData == null) { cd = this._dbContext.Class.Max(x => x.ClassCd) + 1; var entity = new Class { ClassCd = cd, ClassName = data.Class, }; this._dbContext.Class.Add(entity); } else { cd = classData.ClassCd; } return(cd); }
public async Task <ActionResult <BookItem> > PostBookItem(BookItem item) { bookContext.BookItems.Add(item); await bookContext.SaveChangesAsync(); return(CreatedAtAction(nameof(GetBookItem), new { isbn = item.isbn }, item)); }
/// <summary> /// 本の登録 /// </summary> /// <param name="data">データ</param> /// <param name="authorCd">著者コード</param> /// <param name="publisherCd">出版社コード</param> /// <param name="classCd">分類コード</param> private int InsertBook(BookItem data, int authorCd, int publisherCd, int classCd) { var autoNum = 0; var book = this._dbContext.Book.FirstOrDefault(x => x.Date == data.DateTime && x.Title == data.Title); if (book == null) { autoNum = this._dbContext.Book.Max(x => x.Autonumber) == 0 ? 1 : this._dbContext.Book.Max(x => x.Autonumber) + 1; var entity = new Book { Autonumber = autoNum, Date = data.DateTime, Title = data.Title, AuthorCd = authorCd, PublisherCd = publisherCd, ClassCd = classCd, PublishYear = data.PublishYear, PageCount = data.PageCount, RecommendFlg = data.RecommendFlg, DeleteFlg = "0", }; this._dbContext.Book.Add(entity); } return(autoNum); }
private void OpenBook(BookItem Book) { ThisBook = Book; Shared.CurrentBook = Book; PageProcessor.ReadSecondaryTile(Book); CacheStateStory.Begin(); BookLoading = true; if (Book.IsEx()) { Book.XSetProp("Mode", X.Const <string>(XProto.WProtocols, "ACTION_BOOK_META")); } BookLoader BL = new BookLoader(BookLoadComplete); BL.Load(Book, true); BL.LoadIntro(Book, true); BL.LoadCover(Book, true); SyncAnchors(); SetContext(); }
/// <summary> /// 加载开局库 /// </summary> public void LoadBook() { TextAsset assets = Resources.Load <TextAsset>("BOOK"); byte[] buffer = assets.bytes; bookSize = buffer.Length / 8; if (bookSize == 0) { return; } else if (bookSize > BOOK_SIZE) { bookSize = BOOK_SIZE; } bookTable = new BookItem[bookSize]; int offset = 0; for (int i = 0; i < bookSize; i++) { BookItem item = new BookItem(); item.bookLock = System.BitConverter.ToUInt32(buffer, offset); offset += 4; item.mv = System.BitConverter.ToUInt16(buffer, offset); offset += 2; item.value = System.BitConverter.ToUInt16(buffer, offset); offset += 2; bookTable[i] = item; } }
public async Task UpdateBook_WhenValidModelIsSent_ReturnsOk() { //Arrange var storedBook = new BookItem { BookId = "1", AuthorId = "1", Name = "1" }; await Facade.InsertBookAsync(storedBook); var model = new BookModel { BookId = "1", AuthorId = "000", Name = "000" }; var stringContent = new StringContent(model.MapToJson(), Encoding.UTF8, "application/json"); var uri = "api/books/1"; //Act var httpResponse = await HttpClient.PutAsync(uri, stringContent); //Assert httpResponse.StatusCode.Should().Be(HttpStatusCode.OK); var responseContent = await httpResponse.ReadContentAs <BookModel>(); responseContent.Should().NotBeNull(); var storedBookResult = await Facade.LoadBookAsync(model.BookId); storedBookResult.Value.Should().BeEquivalentTo(model); }
public async Task <IActionResult> PutBookItem([FromRoute] int id, [FromBody] BookItem bookItem) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != bookItem.Id) { return(BadRequest()); } _context.Entry(bookItem).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BookItemExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ReviewsInput( BookItem B ) :this() { IsReview = false; StringResources stx = new StringResources( "AppBar" ); Title.Text = stx.Str( "AddComment" ); }
public static List<ChapterItem> GetChapters(BookItem item, WebRuleItem rule, HtmlExpand html) { var chapters = new List<ChapterItem>(); var ms = html.Narrow(rule.CatalogBegin, rule.CatalogEnd) .Matches(@"<a[^<>]+?href=""?(?<href>[^""<>\s]+)[^<>]*>(?<title>[\s\S]+?)</a>"); foreach (Match match in ms) { var url = match.Groups["href"].Value; chapters.Add(new ChapterItem(match.Groups["title"].Value, UrlHelper.GetAbsolute(item.Url, url), LocalHelper.GetSafeFile(url))); } return chapters; }
public AutoCache( BookItem b, Action<BookItem> Handler ) : this() { // fitm = f; ThisBook = b; OnComplete = Handler; StatusText = "Ready"; if ( CurrentCount < AutoLimit ) { wCache.InitDownload( ThisBook.Id , X.Call<XKey[]>( XProto.WRequest, "GetBookTOC", ThisBook.Id ) , cacheInfo, cacheInfoFailed, false ); } }
public static List<ChapterItem> GetBook(ref BookItem item, WebRuleItem rule) { var html = new HtmlExpand(); html.SetUrl(item.Url); if (!string.IsNullOrWhiteSpace(rule.CoverBegin) || !string.IsNullOrWhiteSpace(rule.CoverEnd)) { item.Image = html.GetCover(rule.CoverBegin, rule.CoverEnd); } if (!string.IsNullOrWhiteSpace(rule.AuthorBegin) || !string.IsNullOrWhiteSpace(rule.AuthorEnd)) { item.Author = html.GetAuthor(rule.AuthorBegin, rule.AuthorEnd); } if (!string.IsNullOrWhiteSpace(rule.DescriptionBegin) || !string.IsNullOrWhiteSpace(rule.DescriptionEnd)) { item.Description = html.GetDescription(rule.DescriptionBegin, rule.DescriptionEnd); } var chapters = GetChapters(item, rule, html); item.Count = chapters.Count; return chapters; }
public void Load( BookItem b, bool useCache = false ) { CurrentBook = b; if( b.IsLocal ) { OnComplete( b ); return; } if ( b is BookInstruction ) { LoadInstruction( ( BookInstruction ) b, useCache ); return; } string id = b.Id; string Mode = X.Const<string>( XProto.WProtocols, "ACTION_BOOK_INFO" ); if( CurrentBook.XTest( XProto.BookItemEx ) ) { Mode = CurrentBook.XField<string>( "Mode" ); } XKey[] ReqKeys = X.Call<XKey[]>( XProto.WRequest, "DoBookAction", Mode, id ); if ( useCache ) { string cacheName = X.Call<string>( XProto.WRuntimeCache, "GetCacheString", new object[] { ReqKeys } ); if ( Shared.Storage.FileExists( FileLinks.ROOT_CACHE + cacheName ) ) { ExtractBookInfo( Shared.Storage.GetString( FileLinks.ROOT_CACHE + cacheName ), id ); return; } } X.Instance<IRuntimeCache>( XProto.WRuntimeCache ) .InitDownload( id, ReqKeys, PrelaodBookInfo, PrelaodBookInfo, true ); }
public void Load( BookItem b ) { // b is null when back button is pressed before BookLoader load if ( b == null ) return; Shared.LoadMessage( "LoadingVolume" ); CurrentBook = b; if ( b.IsLocal || ( !b.NeedUpdate && Shared.Storage.FileExists( CurrentBook.TOCPath ) ) ) { OnComplete( b ); } else if ( b is BookInstruction ) { LoadInst( ( BookInstruction ) b ); } else // wenku8 Protocol { IRuntimeCache wCache = X.Instance<IRuntimeCache>( XProto.WRuntimeCache ); // This occurs when tapping pinned book but cache is cleared wCache.InitDownload( CurrentBook.Id , X.Call<XKey[]>( XProto.WRequest, "GetBookTOC", CurrentBook.Id ) , ( DRequestCompletedEventArgs e, string id ) => { Shared.Storage.WriteString( CurrentBook.TOCPath, Manipulation.PatchSyntax( e.ResponseString ) ); Shared.Storage.WriteString( CurrentBook.TOCDatePath, CurrentBook.RecentUpdateRaw ); OnComplete( b ); } , ( string RequestURI, string id, Exception ex ) => { OnComplete( b ); } , false ); } }
private void LoadBookInfo( LocalTextDocument Doc ) { IEnumerable<UIElement> Modules = MasterContainer.Children; SetTemplateTOC( ThisBook = X.Instance<BookItem>( XProto.BookItemEx, Doc ) ); }
private void LoadBookInfo( BookItem Book ) { BookLoader BL = new BookLoader( ( NaN ) => { if ( SkipThisPage ) { new VolumeLoader( GoToContentReader ).Load( ThisBook ); return; } UpdateBookInfoSection( Book ); if ( ViewTOC ) { new VolumeLoader( SetTemplateTOC ).Load( ThisBook ); } } ); if ( ViewComments ) SetTemplateComment( Book ); BL.Load( ThisBook, useCache ); }
// Loading itself is resources intensive // But dispatching itself is not private void OnComplete( BookItem b ) { Worker.UIInvoke( () => { CompleteHandler( b ); } ); }
private void SetTemplateComment( BookItem b ) { if ( b is BookInstruction ) { CommentFrame.Content = new Sharers.ScriptDetails( b, CommentFrame ); } else { CommentFrame.Content = new BookInfoControls.Comments( b ); } }
private void OpenType( object parameter ) { useCache = true; if ( parameter is string ) { useCache = false; LoadBookInfo( parameter.ToString() ); } else if ( parameter is LocalTextDocument ) { LoadBookInfo( parameter as LocalTextDocument ); } else if ( parameter is BookItem ) { useCache = false; ThisBook = ( BookItem ) parameter; LoadBookInfo( ThisBook as BookItem ); } }
private void UpdateBookInfoSection( BookItem b ) { BookInfoSection.DataContext = b; }
public void LoadIntro( BookItem b, bool useCache = true ) { if ( b is BookInstruction ) return; CurrentBook = b; // Description if ( Shared.Storage.FileExists( b.IntroPath ) ) { CurrentBook.Intro = "OK"; } else { X.Instance<IRuntimeCache>( XProto.WRuntimeCache ).InitDownload( b.Id , X.Call<XKey[]>( XProto.WRequest, "GetBookIntro", b.Id ) , SaveIntro, IntroFailed, useCache ); } }
internal static void DownloadVolume( BookItem ThisBook, Volume Vol ) { if ( ThisBook is BookInstruction ) { Chapter[] Chs = Vol.ChapterList; int i = 0; int l = Chs.Length; ChapterLoader Loader = null; Loader = new ChapterLoader( ThisBook, C => { C.UpdateStatus(); if ( i < l ) { Loader.Load( Chs[ i++ ] ); } } ); Loader.Load( Chs[ i++ ] ); return; } Worker.ReisterBackgroundWork( () => { string id = ThisBook.Id; string CVid = Vol.vid; foreach ( Chapter c in Vol.ChapterList ) { if ( !c.IsCached ) { Logger.Log( ID, "Registering: " + c.ChapterTitle, LogType.DEBUG ); App.RuntimeTransfer.RegisterRuntimeThread( X.Call<XKey[]>( XProto.WRequest, "GetBookContent", id, c.cid ) , c.ChapterPath, Guid.NewGuid() , Uri.EscapeDataString( ThisBook.Title ) + "&" + Uri.EscapeDataString( Vol.VolumeTitle ) + "&" + Uri.EscapeDataString( c.ChapterTitle ) , c.IllustrationPath ); } } App.RuntimeTransfer.StartThreadCycle( ( a, b ) => { LoadComplete( a, b ); Worker.UIInvoke( () => { foreach ( Chapter C in Vol.ChapterList ) C.UpdateStatus(); } ); } ); App.RuntimeTransfer.ResumeThread(); } ); }
private void cmdAdd_Click(object sender, EventArgs e) { if (_AddNewBookMode) { BookItem item = new BookItem(this._Title, this._Authors, this._Notes); _Broker.Save(item); } else { if (_Broker.SelectedItem == null) { BookItem item = new BookItem(this._Title, this._Authors, this._Notes); _Broker.Save(item); } else { _Broker.SelectedItem.Text = _Notes; _Broker.SelectedItem.Author = _Authors; _Broker.SelectedItem.Title = _Title; _Broker.Save(_Broker.SelectedItem); } } this.Close(); }
private async Task CacheCover( BookItem B ) { if( Shared.Storage.FileExists( CurrentBook.CoverPath ) ) { SetCover( B ); return; } if( !string.IsNullOrEmpty( B.CoverSrcUrl ) ) { TaskCompletionSource<int> Awaitable = new TaskCompletionSource<int>(); // Set the referer, as it is required by some site such as fanfiction.net new RuntimeCache( a => { HttpRequest R = new WHttpRequest( a ); R.EN_UITHREAD = true; if ( !string.IsNullOrEmpty( B.OriginalUrl ) ) { R.RequestHeaders[ HttpRequestHeader.Referer ] = B.OriginalUrl; } return R; } ).GET( new Uri( B.CoverSrcUrl ), ( a, b ) => { CoverDownloaded( a, b ); Awaitable.TrySetResult( 0 ); } // Failed handler , ( a, b, c ) => { Awaitable.TrySetResult( 0 ); }, false ); await Awaitable.Task; } }
private void _begin() { var item = new BookItem(Name, Source, Kind, Url); var conn = DatabaseHelper.Open(); var count = DatabaseHelper.Find<BookItem>("count(Name)", "Name = @name", new SQLiteParameter("@name", item.Name)); if (Convert.ToInt32(count) > 0) { DatabaseHelper.Close(); _showMessage("书名存在,请更改!"); RingVisibility = Visibility.Collapsed; return; } var chapters = new List<ChapterItem>(); var watch = new Stopwatch(); watch.Start(); var rule = new WebRuleItem(); if (item.Source == BookSources.网络) { rule = DatabaseHelper.GetRule(item.Url); if (rule == null) { DatabaseHelper.Close(); _showMessage("网站规则不存在,请添加!"); RingVisibility = Visibility.Collapsed; watch.Stop(); return; } chapters.AddRange(Helper.HttpHelper.GetBook(ref item, rule)); } else { chapters.AddRange(LocalHelper.GetChapters(item.Url)); } var id = DatabaseHelper.InsertId<BookItem>( "Name, Image, Description, Author, Source, Kind, Url, `Index`, Count, Time", "@name,@image,@description,@author,@source,@kind, @url, @index, @count, @time", new SQLiteParameter("@name", item.Name), new SQLiteParameter("@image", item.Image), new SQLiteParameter("@description", item.Description), new SQLiteParameter("@author", item.Author), new SQLiteParameter("@source", item.Source), new SQLiteParameter("@kind", item.Kind), new SQLiteParameter("@url", item.Url), new SQLiteParameter("@index", item.Index), new SQLiteParameter("@count", item.Count), new SQLiteParameter("@time", item.Time)); LocalHelper.CreateTempDir(); //if (item.Source == BookSources.网络) //{ // var result = Parallel.ForEach<ChapterItem>(chapters, chapter => // { // var i = 0; // if (File.Exists(LocalHelper.TempDir + chapter.Content)) // { // return; // } // OneBegin: // var html = new HtmlExpand(); // try // { // html.SetUrl(chapter.Url); // 超时 // html.Narrow(rule.ChapterBegin, rule.ChapterEnd); // LocalHelper.WriteTemp( // html.GetText(rule.Replace), chapter.Content); // } // catch (Exception ex) // { // if (i < 5) // { // Thread.Sleep(20000); // goto OneBegin; // } // LocalHelper.WriteLog( // $"{ex.Message} 网址 {chapter.Url}"); // } // }); // while (!result.IsCompleted) // { // Thread.Sleep(1000); // } //} var writer = new StreamWriter($"{LocalHelper.TempDir}{Name}.txt", false, Encoding.UTF8); foreach (var chapter in chapters) { writer.WriteLine(chapter.Name); writer.WriteLine(); writer.WriteLine(LocalHelper.ReadTemp(chapter.Content)); writer.WriteLine(); writer.WriteLine(); } writer.Close(); try { DbTransaction trans = conn.BeginTransaction(); try { foreach (var chapter in chapters) { DatabaseHelper.Insert<ChapterItem>( "Name, Content, BookId, Url", "@Name, @Content, @BookId, @Url", new SQLiteParameter("@Name", chapter.Name), new SQLiteParameter("@Content", LocalHelper.ReadTemp(chapter.Content)), new SQLiteParameter("@BookId", id), new SQLiteParameter("@Url", chapter.Url)); } trans.Commit(); } catch (Exception ex) { trans.Rollback(); LocalHelper.WriteLog(ex.Message); _showMessage("章节插入失败,已进行回滚!"); } } catch (Exception ex) { LocalHelper.WriteLog(ex.Message); } DatabaseHelper.Close(); _addItem.Execute(item); RingVisibility = Visibility.Collapsed; Name = Url = string.Empty; watch.Stop(); _showMessage("执行完成!耗时:" + watch.Elapsed); }
private async Task ExtractProps( BookItem Inst, string Content ) { foreach( PropExt Extr in PropDefs ) { if ( !Extr.Enabled ) continue; string PropValue = MatchSingle( Extr, Content ); if ( Extr.SubProc.HasProcedures ) { ProcManager.PanelMessage( this, () => Res.RSTR( "SubProcRun" ), LogType.INFO ); ProcPassThru PPass = new ProcPassThru( new ProcConvoy( this, Inst ) ); ProcConvoy SubConvoy = await Extr.SubProc.CreateSpider().Crawl( new ProcConvoy( PPass, PropValue ) ); // Process ReceivedConvoy if ( SubConvoy.Payload is string ) PropValue = ( string ) SubConvoy.Payload; else if ( SubConvoy.Payload is IEnumerable<string> ) PropValue = string.Join( "\n", ( IEnumerable<string> ) SubConvoy.Payload ); else if ( SubConvoy.Payload is IStorageFile ) PropValue = await ( ( IStorageFile ) SubConvoy.Payload ).ReadString(); else if ( SubConvoy.Payload is IEnumerable<IStorageFile> ) PropValue = await ( ( IEnumerable<IStorageFile> ) SubConvoy.Payload ).First().ReadString(); else continue; } // If the website split a single property into serveral pages // That website is stupid. Would not support. if( !Inst.ReadParam( Extr.PType.ToString(), PropValue.ToCTrad() ) ) { ProcManager.PanelMessage( this, () => Res.RSTR( "InvalidParam", Extr.PType ), LogType.WARNING ); } } }
private async void GoToContentReader( BookItem b ) { TOCData = new TOCSection( b ); if ( TOCData.AnchorAvailable ) { await Dispatcher.RunAsync( CoreDispatcherPriority.Normal , () => Frame.Navigate( typeof( ContentReader ), TOCData.AutoAnchor ) ); return; } EpisodeStepper ES = new EpisodeStepper( new VolumesInfo( b ) ); ES.StepNext(); await OneDriveRsync(); await Dispatcher.RunAsync( CoreDispatcherPriority.Normal , () => Frame.Navigate( typeof( ContentReader ) , new Chapter( ES.EpTitle, b.Id, ES.Vid, ES.Cid ) ) ); }
private void SetTemplateTOC( BookItem b ) { TOCData = new TOCSection( b ); TOCData.TemplateSelector.IsHorizontal = LayoutSettings.HorizontalTOC; TOCSection.DataContext = TOCData; TOCFloatSection.DataContext = TOCData; TOCData.SetViewSource( VolumesViewSource ); if ( VolList != null && 0 < VolList.Items.Count() ) { VolList.SelectedIndex = 0; } }
public async void SuggestUpload( BookItem b ) { BindItem = await LoadFromSHHub( b.Id, AccessToken ); if ( BindItem != null ) { await Dispatcher.RunIdleAsync( ( x ) => SetTemplate() ); } else { await Dispatcher.RunIdleAsync( x => ParentFrame.Content = new ScriptUpload( b, UploadReturn ) ); } }
public ScriptDetails( BookItem b, Frame ParentFrame ) :this() { this.ParentFrame = ParentFrame; AccessToken = ( string ) new TokenManager().GetAuthById( b.Id )?.Value; SuggestUpload( b ); }
/// <summary> /// Initializes a new instance of the ReadViewModel class. /// </summary> public ReadViewModel() { Messenger.Default.Register<NotificationMessageAction<int>>(this, "readViewer", m => { _readViewer = m; }); Messenger.Default.Register<NotificationMessageAction<BookItem>>(this, "read", m => { _readItem = m; _book = (BookItem) m.Sender; _loading(); }); }
public ReaderView( BookItem B, Chapter C ) :this() { BindChapter = C; Anchors = new CustomAnchor( B ); CL = new ChapterLoader( B, SetContent ); }
private void LoadBookInfo( string id ) { string[] Argv = id.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ); if ( Argv.Length == 2 ) { string Mode = Argv[ 0 ]; id = Argv[ 1 ]; if ( Mode == "Spider" ) { // XXX: TODO return; } else if ( Mode == "Local" ) { // XXX: TODO return; } // Commencing Level2 initializations new global::wenku8.System.Bootstrap().Level2(); } BookItem BookEx = X.Instance<BookItem>( XProto.BookItemEx, id ); BookEx.XSetProp( "Mode" , X.Const<string>( XProto.WProtocols, "ACTION_BOOK_META" ) ); ThisBook = BookEx; if ( SkipThisPage ) { new VolumeLoader( GoToContentReader ).Load( ThisBook ); return; } if ( ViewInfo ) { BookLoader BL = new BookLoader( UpdateBookInfoSection ); BL.Load( ThisBook, true ); BL.LoadIntro( ThisBook, true ); } if ( ViewTOC ) { new VolumeLoader( SetTemplateTOC ).Load( ThisBook ); } if ( ViewComments ) { SetTemplateComment( ThisBook ); } }
private void Dispose() { NavigationHandler.OnNavigatedBack -= OnBackRequested; ThisBook = null; TOCData = null; VolList = null; try { // Try Dispose Worker.UIInvoke( () => { TOCSection.DataContext = null; CommentFrame.Content = null; BookInfoSection.DataContext = null; } ); } catch ( Exception ) { } }
private void SetCover( BookItem B ) { Worker.UIInvoke( () => { BitmapImage bmp = new BitmapImage(); bmp.SetSourceFromUrl( B.CoverPath ); B.Cover = bmp; } ); }