/// <summary> /// Either retrieve existing GSC or create a new one /// GSCs are cached using a combination of the user's principal ID and the scopes of the token used to authenticate /// </summary> /// <param name="attribute">Token attribute with either principal ID or ID token</param> /// <returns>Authenticated GSC</returns> public virtual async Task <IGraphServiceClient> GetMSGraphClientFromTokenAttributeAsync(TokenBaseAttribute attribute, CancellationToken cancellationToken) { string token = await this._tokenProvider.ConvertAsync(attribute, cancellationToken); string principalId = GetTokenOID(token); var key = string.Concat(principalId, " ", GetTokenOrderedScopes(token)); CachedClient cachedClient = null; // Check to see if there already exists a GSC associated with this principal ID and the token scopes. if (_clients.TryGetValue(key, out cachedClient)) { // Check if token is expired if (cachedClient.expirationDate < DateTimeOffset.Now.ToUnixTimeSeconds()) { // Need to update the client's token & expiration date // $$ todo -- just reset token instead of whole new authentication provider? _clientProvider.UpdateGraphServiceClientAuthToken(cachedClient.client, token); cachedClient.expirationDate = GetTokenExpirationDate(token); } return(cachedClient.client); } else { cachedClient = new CachedClient { client = _clientProvider.CreateNewGraphServiceClient(token), expirationDate = GetTokenExpirationDate(token), }; _clients.TryAdd(key, cachedClient); return(cachedClient.client); } }
async void ChapterPageViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var cvm = sender as ChapterViewModel; if (cvm != null && e.PropertyName == "DataContext") { CurrentChapter = cvm.DataContext; var id = CurrentChapter.ParentVolumeId; if (CurrentSeries == null || CurrentSeries.Id != CurrentChapter.ParentSeriesId) { try { CurrentSeries = await CachedClient.GetSeriesAsync(cvm.ParentSeriesId); } catch (Exception exception) { //MessageBox.Show("Exception happend when loading current novel Series."); Debug.WriteLine("Failed to retrive series data when loading a new chapter."); } } if (CurrentSeries == null) { return; } var volume = CurrentSeries.Volumes.FirstOrDefault(vol => vol.Id == id); if (volume != null) { CurrentVolume = volume; } else { throw new Exception("Current Chapter goes beyoung Current Series."); } } }
public async Task LoadSeriesIndexDataAsync() { if (IsLoaded) { return; } IsLoading = true; try { var serIndex = await CachedClient.GetSeriesIndexAsync(); var cgs = new Windows.Globalization.Collation.CharacterGroupings(); SeriesIndex = (from series in serIndex group series by cgs.Lookup(series.Title) into g orderby g.Key select g).ToList(); IsLoaded = true; } catch (Exception exception) { Debug.WriteLine("Exception when retrieving series index : " + exception.Message); //throw exception; //MessageBox.Show(exception.Message, "Data error", MessageBoxButton.OK); } IsLoading = false; }
public CachedClientTest(ConnectionMultiplexerFixture multiplexerFixture) { var manager = new CachedClientManager(multiplexerFixture.Multiplexer); _client = manager.GetClient(0); _client.Execute("flushdb"); _client.RequestDelay = 10; _client.Connect(); }
private async Task RemoveRecentItem(HistoryItemViewModel hvm) { ViewModel.IsLoading = true; await CachedClient.DeleteSeries(hvm.Position.SeriesId); ViewModel.RecentSection.Remove(hvm); var recentItem = AppGlobal.RecentList.FirstOrDefault(it => it.Position.SeriesId == hvm.Position.SeriesId); if (recentItem != null) { AppGlobal.RecentList.Remove(recentItem); await AppGlobal.SaveHistoryDataAsync(); } ViewModel.IsLoading = false; }
private async Task RefreshCruptedImageItem(Grid iv) { var imageContent = iv.FindName("ImageContent") as Image; var lvm = imageContent.DataContext as LineViewModel; if (lvm == null) { return; } var bitmap = imageContent.Source as BitmapImage; if (bitmap == null) { return; } var uri = bitmap.UriSource.AbsoluteUri; if (uri.StartsWith("ms-appdata")) { var textContent = iv.FindName("TextContent") as TextBlock; var commentIndicator = iv.FindName("CommentIndicator") as Rectangle; var progressIndicator = iv.FindName("ProgressBar") as ProgressBar; var imagePlaceholder = iv.FindName("ImagePlaceHolder") as Windows.UI.Xaml.Shapes.Path; var remoteUri = lvm.Content; textContent.Text = ImageLoadingTextPlaceholder; imagePlaceholder.Visibility = Windows.UI.Xaml.Visibility.Visible; imagePlaceholder.Opacity = 1; imageContent.Visibility = Windows.UI.Xaml.Visibility.Visible; textContent.TextAlignment = TextAlignment.Center; textContent.Opacity = 1; imageContent.Opacity = 0; progressIndicator.Opacity = 1; imageContent.ImageOpened -= imageContent_ImageOpened; bitmap.DownloadProgress -= Image_DownloadProgress; bitmap.UriSource = new Uri(remoteUri); bitmap.DownloadProgress += Image_DownloadProgress; imageContent.ImageOpened += imageContent_ImageOpened; await CachedClient.DeleteIllustationAsync(remoteUri); } // else is Network Issue }
/// <summary> /// Either retrieve existing GSC or create a new one /// GSCs are cached using a combination of the user's principal ID and the scopes of the token used to authenticate /// </summary> /// <param name="attribute">Token attribute with either principal ID or ID token</param> /// <returns>Authenticated GSC</returns> public virtual async Task <IGraphServiceClient> GetMSGraphClientAsync(TokenAttribute attribute) { string token = await this._tokenExtension.GetAccessTokenAsync(attribute); string principalId = GetTokenOID(token); var key = string.Concat(principalId, " ", GetTokenOrderedScopes(token)); CachedClient client = null; // Check to see if there already exists a GSC associated with this principal ID and the token scopes. if (this._clients.TryGetValue(key, out client)) { // Check if token is expired if (client.expirationDate < DateTimeOffset.Now.ToUnixTimeSeconds()) { // Need to update the client's token & expiration date // $$ todo -- just reset token instead of whole new authentication provider? client.client.AuthenticationProvider = new DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token); return(Task.CompletedTask); }); client.expirationDate = GetTokenExpirationDate(token); } return(client.client); } else { client = new CachedClient { client = new GraphServiceClient( new DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token); return(Task.CompletedTask); })), expirationDate = GetTokenExpirationDate(token), }; this._clients.TryAdd(key, client); return(client.client); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } Debug.WriteLine("AppOnLaunched"); #endif #if WINDOWS_UWP SyncAppAccentColor(); //var search = await LightKindomHtmlClient.SearchBookAsync("青春"); //var featured = await LightKindomHtmlClient.GetFeaturedBooks(); //var comments = await LightKindomHtmlClient.GetCommentsAsync("797", "72"); //var chptr = await LightKindomHtmlClient.GetChapterAsync("797", "129", "72"); //var chptr = await LightKindomHtmlClient.GetSeriesAsync("72"); //var chapter = new Uri("http://linovel.com/book/read?chapterId=798&volId=129&bookId=72"); //var client = new Windows.Web.Http.HttpClient(); //var content = await client.GetStringAsync(chapter); //var result = await LightKindomHtmlClient.GetCommentedLinesListAsync("4516"); //var anotherresult = await LightKindomHtmlClient.GetCommentsAsync("36","4516"); //var chptr = await LightKindomHtmlClient.GetSeriesIndexAsync(); //var result = await LightKindomHtmlClient.SearchBookAsync("青春"); #endif mainDispatcher = Window.Current.Dispatcher; mainViewId = ApplicationView.GetForCurrentView().Id; Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { ExtendedSplash extendedSplash; if (Window.Current.Content == null) { extendedSplash = new ExtendedSplash(e.SplashScreen); } else { extendedSplash = Window.Current.Content as ExtendedSplash; } extendedSplash.RegisterFrameArriveDimmsion(); // Create a Frame to act as the navigation context and navigate to the first page rootFrame = extendedSplash.RootFrame; // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 3; //Associate the frame with a SuspensionManager key try { SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); } catch (Exception) { } Window.Current.Content = extendedSplash; Window.Current.Activate(); // Place the frame in the current Window // Window.Current.Content = rootFrame; } else { Window.Current.Activate(); } #region Preloading #if WINDOWS_PHONE_APP //Windows.UI.ViewManagement.ApplicationView.GetForCurrentView() // .SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseVisible); var statusBar = StatusBar.GetForCurrentView(); statusBar.BackgroundOpacity = 0; statusBar.ForegroundColor = (Windows.UI.Color)Resources["AppBackgroundColor"]; #endif //return; await AppGlobal.LoadHistoryDataAsync(); await AppGlobal.LoadBookmarkDataAsync(); await CachedClient.InitializeCachedSetAsync(); AppGlobal.RefreshAutoLoadPolicy(); #endregion if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { #if WINDOWS_PHONE_APP rootFrame.ContentTransitions = new TransitionCollection() { new NavigationThemeTransition() { DefaultNavigationTransitionInfo = new ContinuumNavigationTransitionInfo() } }; #endif await SuspensionManager.RestoreAsync(); if (rootFrame.Content != null && Window.Current.Content != rootFrame) { Window.Current.Content = rootFrame; return; } } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue } } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif } // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter bool navResult = true; if (string.IsNullOrEmpty(e.Arguments)) { var entity = rootFrame.BackStack.FirstOrDefault(pse => pse.SourcePageType == typeof(HubPage)); if (rootFrame.CurrentSourcePageType != typeof(HubPage) && entity == null) { navResult = rootFrame.Navigate(typeof(HubPage), e.Arguments); } else { while (rootFrame.CurrentSourcePageType != typeof(HubPage) && rootFrame.CanGoBack) { rootFrame.GoBack(); } } } else { var entity = rootFrame.BackStack.FirstOrDefault(pse => pse.SourcePageType == typeof(ReadingPage)); if (entity == null && rootFrame.CurrentSourcePageType != typeof(ReadingPage)) { navResult = rootFrame.Navigate(typeof(ReadingPage), e.Arguments); } else { while (rootFrame.CurrentSourcePageType != typeof(ReadingPage) && rootFrame.CanGoBack) { rootFrame.GoBack(); } var page = rootFrame.Content as ReadingPage; var navigationId = NovelPositionIdentifier.Parse((string)e.Arguments); if (navigationId.SeriesId != page.ViewModel.SeriesId.ToString()) { navResult = rootFrame.Navigate(typeof(ReadingPage), e.Arguments); } } } if (!navResult) { navResult = rootFrame.Navigate(typeof(HubPage), null); } AppGlobal.Settings.UpdateSavedAppVersion(); //App.CurrentState.SignInAutomaticlly(); // Ensure the current window is active //Window.Current.Activate(); }
public void SetUp() { _client = new CachedClient( _target ); _foo = GetBytes( "foo" ); }
public override WebResponse GetResponse() { return(CachedClient.GetResponse()); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { var series = ViewModel; if (e.NavigationMode == NavigationMode.Back) { return; } //Uri e.Uri string serId = NavigationContext.QueryString["id"]; string volId = null; if (NavigationContext.QueryString.ContainsKey("volume")) { volId = NavigationContext.QueryString["volume"]; } string cptId = null; if (NavigationContext.QueryString.ContainsKey("chapter")) { cptId = NavigationContext.QueryString["chapter"]; } int lineNo = 1; if (NavigationContext.QueryString.ContainsKey("line")) { string line = NavigationContext.QueryString["line"]; lineNo = int.Parse(line); } // Volume specifid view if (String.IsNullOrWhiteSpace(serId) && !String.IsNullOrWhiteSpace(volId)) { ViewModel.IsLoading = true; Volume volData = null; try { volData = await CachedClient.GetVolumeAsync(volId); } catch (Exception exception) { ViewModel.IsLoading = false; MessageBox.Show(exception.Message, "Network issue", MessageBoxButton.OK); NavigationService.GoBack(); return; } serId = volData.ParentSeriesId; ViewModel.Title = volData.Title; ViewModel.VolumeList.Clear(); ViewModel.VolumeList.Add(new VolumeViewModel { DataContext = volData }); ViewModel.Id = serId; App.CurrentVolume = volData; try { var serData = await CachedClient.GetSeriesAsync(serId); for (int i = 0; i < serData.Volumes.Count; i++) { if (serData.Volumes[i].Id == volId) { CurrentVolumeNo = i; break; } } ViewModel.DataContext = serData; if (VolumeViewList.ItemsSource.Count > 0) { VolumeViewList.ItemRealized += VolumeViewList_ItemRealized_ScrollToCurrentLine; } //App.CurrentSeries = serData; } catch (Exception exception) { MessageBox.Show("Exception happend when retriving series data" + exception.Message, "Network issue", MessageBoxButton.OK); } } if (series.Id != serId && !series.IsLoading) { await series.LoadDataAsync(serId); //ViewModel.IsLoading = true; if (VolumeViewList.ItemsSource.Count > 0) { CurrentVolumeNo = 0; VolumeViewList.ItemRealized += VolumeViewList_ItemRealized_ScrollToCurrentLine; } //await Task.WhenAll(ViewModel.VolumeList.Select(vvm => vvm.LoadDataAsync(vvm.Id))); } }