/// <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) { // Get a reference to the SQLite database conn = new SQLiteConnection("sqlitepcldemo.db"); CreateDatabase.LoadDatabase(conn); #if DEBUGEFR if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } 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 if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
/// <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="args">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; if (args.PreviousExecutionState == ApplicationExecutionState.Running) { if (!String.IsNullOrEmpty(args.Arguments)) { ((Frame)Window.Current.Content).Navigate(typeof(ItemDetailPage), args.Arguments); } Window.Current.Activate(); return; } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } if (args.PreviousExecutionState == ApplicationExecutionState.Running) { Window.Current.Activate(); return; } await BreedDataSource.LoadDataAsync(); SearchPane.GetForCurrentView().SuggestionsRequested += OnSuggestionsRequested; // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups")) { throw new Exception("Failed to create initial page"); } } if (!String.IsNullOrEmpty(args.Arguments)) { rootFrame.Navigate(typeof(ItemDetailPage), args.Arguments); Window.Current.Content = rootFrame; Window.Current.Activate(); return; } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (appListener == null) { appListener = new LogEventListener(); appListener.EnableEvents(LogEventSource.Log, EventLevel.Verbose); errorListener = new LogEventListener("Errors"); errorListener.EnableEvents(LogEventSource.Log, EventLevel.Error); LogEventSource.Log.Info("App initialized."); // winRT approach channel = new LoggingChannel("WinRTChannel"); channel.LoggingEnabled += (o, args) => { this.winRtLoggingEnabled = o.Enabled; this.winRtLogLevel = o.Level; }; session = new LoggingSession("WinRTSession"); session.AddLoggingChannel(channel); } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { const string Message = "Restoring saved session state."; LogEventSource.Log.Info(Message); channel.LogMessage(Message, LoggingLevel.Information); await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException ex) { var message = string.Format("Error restoring saved session state: {0}", ex.Message); LogEventSource.Log.Error(message); channel.LogMessage(message, LoggingLevel.Error); //Something went wrong restoring state. //Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(HubPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); const string Msg = "Window activated."; LogEventSource.Log.Info(Msg); channel.LogMessage(Msg, LoggingLevel.Information); }
// Token: 0x0600140A RID: 5130 RVA: 0x000023E2 File Offset: 0x000005E2 public void OnDestroy() { SuspensionManager.Unregister(this); }
private async Task EnsureWindow(IActivatedEventArgs args) { // No matter what our destination is, we're going to need control data loaded - let's knock that out now. // We'll never need to do this again. await ControlInfoDataSource.Instance.GetGroupsAsync(); Frame rootFrame = GetRootFrame(); string savedTheme = ApplicationData.Current.LocalSettings.Values[SelectedAppThemeKey]?.ToString(); if (savedTheme != null) { RootTheme = GetEnum <ElementTheme>(savedTheme); } Type targetPageType = typeof(NewControlsPage); string targetPageArguments = string.Empty; if (args.Kind == ActivationKind.Launch) { if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } targetPageArguments = ((LaunchActivatedEventArgs)args).Arguments; } else if (args.Kind == ActivationKind.Protocol) { Match match; string targetId = string.Empty; switch (((ProtocolActivatedEventArgs)args).Uri?.AbsolutePath) { case string s when IsMatching(s, "/category/(.*)"): targetId = match.Groups[1]?.ToString(); if (ControlInfoDataSource.Instance.Groups.Any(g => g.UniqueId == targetId)) { targetPageType = typeof(SectionPage); } break; case string s when IsMatching(s, "/item/(.*)"): targetId = match.Groups[1]?.ToString(); if (ControlInfoDataSource.Instance.Groups.Any(g => g.Items.Any(i => i.UniqueId == targetId))) { targetPageType = typeof(ItemPage); } break; } targetPageArguments = targetId; bool IsMatching(string parent, string expression) { match = Regex.Match(parent, expression); return(match.Success); } } rootFrame.Navigate(targetPageType, targetPageArguments); ((Microsoft.UI.Xaml.Controls.NavigationViewItem)(((NavigationRootPage)(Window.Current.Content)).NavigationView.MenuItems[0])).IsSelected = true; // Ensure the current window is active Window.Current.Activate(); }
// Token: 0x06000AF8 RID: 2808 RVA: 0x00005374 File Offset: 0x00003574 public override void OnDestroy() { base.OnDestroy(); SuspensionManager.Unregister(this); }
/// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// <see cref="NavigationHelper.LoadState"/> /// and <see cref="NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Provides data for navigation methods and event /// handlers that cannot cancel the navigation request.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); SpeechRecognitionResult speechRecognitionResult = e.Parameter as SpeechRecognitionResult; string voiceCommandName = speechRecognitionResult.RulePath[0]; string navigationTarget = speechRecognitionResult.SemanticInterpretation.Properties["NavigationTarget"][0]; IReadOnlyDictionary <string, IReadOnlyList <string> > properties = speechRecognitionResult.SemanticInterpretation.Properties; UriBuilder uri = null; MessageDialog mbox = null; switch (voiceCommandName) { case "ChangeAllLightState": { StorageHelper.SelectedBulbs = StorageHelper.Bulbs; foreach (LifxBulb bulb in StorageHelper.SelectedBulbs) { await bulb.SetPowerStateCommand(properties["LightState"][0]); } } break; case "ChaneOneLightState": case "ChangeOneLightStateAlternate": { StorageHelper.SelectedBulb = StorageHelper.GetBulb(properties["BulbName"][0], true); await StorageHelper.SelectedBulbs[0].SetPowerStateCommand(properties["LightState"][0]); } break; case "ChangeAllLightColour": { string colourname = properties["Colour"][0].Replace(" ", string.Empty); try { StorageHelper.SelectedBulbs = StorageHelper.Bulbs; LifxColour colour = LifxColour.ColorToLifxColour(colourname); foreach (LifxBulb bulb in StorageHelper.SelectedBulbs) { bulb.Colour = colour; await bulb.SetColorCommand(colour, 0); } } catch (ColorNotFoundException) { mbox = new MessageDialog(StorageHelper.ErrorMessages.GetString("ColourNotFound_Voice"), "Colour Not Found"); } } break; case "ChangeOneLightColour": { string colourname = properties["Colour"][0].Replace(" ", string.Empty); string uriString = string.Empty; try { LifxColour colour = LifxColour.ColorToLifxColour(colourname); StorageHelper.SelectedBulb = StorageHelper.GetBulb(properties["BulbName"][0], true); await StorageHelper.SelectedBulbs[0].SetColorCommand(LifxColour.ColorToLifxColour(colourname), 0); //uriString = typeof(VoiceCommandPage).ToString() + "?BulbName=" + properties["BulbName"][0] + "&Colour=" + colourname; //uri = new UriBuilder(uriString); } catch (BulbNotFoundException) { mbox = new MessageDialog(StorageHelper.ErrorMessages.GetString("BulbNotFound_Voice"), "Bulb Not Found"); } catch (ColorNotFoundException) { mbox = new MessageDialog(StorageHelper.ErrorMessages.GetString("ColourNotFound_Voice"), "Colour Not Found"); } } break; default: break; } if (mbox != null) { await mbox.ShowAsync(); } if (StorageHelper.LocalSettings.HasFlag(Settings.CloseOnVoiceCommand)) { App.Current.Exit(); } else { Frame rootFrame = new Frame(); SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); Window.Current.Content = rootFrame; rootFrame.Navigate(typeof(MainPage), uri); } }
/// <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="args">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs args) { 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new CharmFrame { CharmContent = new SettingsFlyout() }; //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); //if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) //{ // // Restore the saved session state only when appropriate // try // { // await SuspensionManager.RestoreAsync(); // } // catch (SuspensionManagerException) // { // //Something went wrong restoring state. // //Assume there is no state and continue // } //} // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter var internet = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile(); if (internet != null && internet.GetNetworkConnectivityLevel() == Windows.Networking.Connectivity.NetworkConnectivityLevel.InternetAccess) { SampleDataSource._sampleDataSource = new SampleDataSource(); SampleDataSource.FavoriteManager.createFavorites(); await SampleDataSource.addMostRecentComic(); //THis is on purpose. They pop in as needed await SampleDataSource.addPreviousN(SampleDataSource.GetGroup("XKCD").Items.Last(), SampleDataSource.GetGroup("XKCD"), 2); SampleDataSource.FavoriteManager.addFavsFromFileAsync(); //SampleDataSource.DownloadAllXKCD(); if (!rootFrame.Navigate(typeof(GroupDetailPage), SampleDataSource.GetGroup("XKCD").Items[0].UniqueId)) { throw new Exception("Failed to create initial page"); } } else { if (!rootFrame.Navigate(typeof(NoInternet))) { throw new Exception("Failed to create no internet page"); } } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoqué lorsque l'application est lancée normalement par l'utilisateur final. D'autres points d'entrée /// sont utilisés lorsque l'application est lancée pour ouvrir un fichier spécifique, pour afficher /// des résultats de recherche, etc. /// </summary> /// <param name="e">Détails concernant la requête et le processus de lancement.</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Ne répétez pas l'initialisation de l'application lorsque la fenêtre comporte déjà du contenu, // assurez-vous juste que la fenêtre est active if (rootFrame == null) { // Créez un Frame utilisable comme contexte de navigation et naviguez jusqu'à la première page rootFrame = new Frame(); //Associez au frame une clé SuspensionManager SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: modifier cette valeur à une taille de cache qui contient à votre application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restaure l'état de session enregistré uniquement lorsque cela est approprié try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Un problème est survenu lors de la restauration de l'état. // Partez du principe que l'état est absent et continuez } } // Placez le frame dans la fenêtre active Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Supprime la navigation tourniquet pour le démarrage. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // Quand la pile de navigation n'est pas restaurée, accédez à la première page, // puis configurez la nouvelle page en transmettant les informations requises en tant que // paramètre if (!rootFrame.Navigate(typeof(HubPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Vérifiez que la fenêtre actuelle est active Window.Current.Activate(); }
/// <summary> /// Initializes a new instance of the <see cref="FrameNavigationService"/> class. /// </summary> /// <param name="frame">The navigation service.</param> public FrameNavigationService(Frame frame, string navigationStackName) { this.frame = frame; SuspensionManager.RegisterFrame(this.frame, navigationStackName); }
/// <summary> /// Вызывается при обычном запуске приложения пользователем. Будут использоваться другие точки входа, /// если приложение запускается для открытия конкретного файла, отображения /// результатов поиска и т. д. /// </summary> /// <param name="e">Сведения о запросе и обработке запуска.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Не повторяйте инициализацию приложения, если в окне уже имеется содержимое, // только обеспечьте активность окна. if (rootFrame == null) { // Создание фрейма, который станет контекстом навигации, и переход к первой странице. rootFrame = new Frame(); // Связывание фрейма с ключом SuspensionManager. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: Измените это значение на размер кэша, подходящий для вашего приложения. rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Восстановление сохраненного состояния сеанса только тогда, когда это необходимо. try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Возникли ошибки при восстановлении состояния. // Предполагаем, что состояние отсутствует, и продолжаем. } } // Размещение фрейма в текущем окне. Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Удаляет турникетную навигацию для запуска. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // Если стек навигации не восстанавливается для перехода к первой странице, // настройка новой страницы путем передачи необходимой информации в качестве параметра // навигации. if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Обеспечение активности текущего окна. Window.Current.Activate(); }
// Token: 0x06003433 RID: 13363 RVA: 0x00029722 File Offset: 0x00027922 public override void OnDestroy() { InstantiateUtility.Destroy(this.m_systemsGameObject); SuspensionManager.Unregister(this); base.OnDestroy(); }
public void StreamListenerEvents() { // STEP 1: prepare the stub data Mock<IResourceFacade> resource = new Mock<IResourceFacade>(); Mock<IAdapterPlugin> connector = new Mock<IAdapterPlugin>(); Mock<IEventState> state = new Mock<IEventState>(); _settings.Setup(x => x.MarketFiltersDirectory).Returns("."); var provider = new StateManager(_settings.Object, connector.Object); var suspensionManager = new SuspensionManager(provider, connector.Object); var fixtureSnapshot = new Fixture { Id = "ABC", Epoch = 0, MatchStatus = "30", Sequence = 1 }; var settledSnapshot = new Fixture { Id = "ABC", Epoch = 3, MatchStatus = "50", Sequence = 5 }; resource.Setup(x => x.Id).Returns("ABC"); resource.Setup(x => x.Content).Returns(new Summary()); resource.Setup(x => x.MatchStatus).Returns(MatchStatus.InRunning); resource.Setup(r => r.StartStreaming()).Raises(r => r.StreamConnected += null, EventArgs.Empty); resource.Setup(r => r.StopStreaming()).Raises(r => r.StreamDisconnected += (e, o) => { }, EventArgs.Empty); //sequence of 3 snapshots middle one should raise an exception resource.SetupSequence(r => r.GetSnapshot()) .Returns(FixtureJsonHelper.ToJson(fixtureSnapshot)) .Returns(String.Empty) .Returns(FixtureJsonHelper.ToJson(settledSnapshot)); // STEP 2: start the listener StreamListener listener = new StreamListener(resource.Object, connector.Object, state.Object, provider, _settings.Object); listener.MonitorEvents(); listener.Start(); listener.ShouldRaise("OnConnected"); listener.ShouldRaise("OnBeginSnapshotProcessing"); listener.ShouldRaise("OnFinishedSnapshotProcessing"); //stream event var update = new Fixture { Id = "ABC", Sequence = 2, MatchStatus = ((int)MatchStatus.MatchOver).ToString(), Epoch = 2, LastEpochChangeReason = new[] { (int)EpochChangeReason.MatchStatus } }; var message = new StreamMessage { Content = update }; listener.ResourceOnStreamEvent(this, new StreamEventArgs(JsonConvert.SerializeObject(message))); listener.ShouldRaise("OnBeginStreamUpdateProcessing"); listener.ShouldRaise("OnFinishedStreamUpdateProcessing"); //as a result of match status change it will get a second snapshot which is String.Empty listener.ShouldRaise("OnError") .WithArgs<StreamListenerEventArgs>(e => e.Exception != null); listener.ShouldRaise("OnSuspend"); //when recovered the IsErrored should clear listener.IsErrored.Should().BeFalse(); listener.ShouldRaise("OnFlagsChanged") .WithArgs<StreamListenerEventArgs>(e => ((StreamListener)e.Listener).IsErrored == false); //simulate stream disconnection listener.ResourceOnStreamDisconnected(null, null); listener.ShouldRaise("OnDisconnected"); listener.Stop(); listener.ShouldRaise("OnStop"); resource.Verify(x => x.GetSnapshot(), Times.Exactly(3), "The StreamListener was supposed to acquire 3 snasphots"); connector.Verify(x => x.ProcessSnapshot(It.IsAny<Fixture>(), It.IsAny<bool>()), Times.Exactly(2)); }
/// <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 override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif 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) { // Create a Frame to act as the navigation context and navigate to the first page. rootFrame = new Frame(); // Associate the frame with a SuspensionManager key. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: Change this value to a cache size that is appropriate for your application. rootFrame.CacheSize = 1; // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate. try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue. } } // Place the frame in the current Window. Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter. if (!rootFrame.Navigate(typeof(PivotPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active. Window.Current.Activate(); }
/// <summary> /// 在应用程序由最终用户正常启动时进行调用。 /// 当启动应用程序以打开特定的文件或显示搜索结果等操作时, /// 将使用其他入口点。 /// </summary> /// <param name="e">有关启动请求和过程的详细信息。</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化, // 只需确保窗口处于活动状态。 if (rootFrame == null) { // 创建要充当导航上下文的框架,并导航到第一页。 rootFrame = new Frame(); // 将框架与 SuspensionManager 键关联。 SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: 将此值更改为适合您的应用程序的缓存大小。 rootFrame.CacheSize = 1; //设置默认语言 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // 仅当合适时才还原保存的会话状态。 try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // 还原状态时出现问题。 // 假定没有状态并继续。 } } // 将框架放在当前窗口中。 Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // 删除用于启动的旋转门导航。 if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // 当导航堆栈尚未还原时,导航到第一页, // 并通过将所需信息作为导航参数传入来配置 // 新页面。 if (!rootFrame.Navigate(typeof(PivotPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // 确保当前窗口处于活动状态。 Window.Current.Activate(); }
public void ShouldNotSetIsFixtureEndedIfThereWasAnErrorProcessingSnapshot() { Mock<IResourceFacade> resource = new Mock<IResourceFacade>(); Mock<IAdapterPlugin> connector = new Mock<IAdapterPlugin>(); Mock<IEventState> state = new Mock<IEventState>(); Mock<ISettings> settings = new Mock<ISettings>(); settings.Setup(x => x.MarketFiltersDirectory).Returns("."); var provider = new StateManager(settings.Object,connector.Object); var suspensionManager = new SuspensionManager(provider, connector.Object); Fixture fixture = new Fixture { Id = "ABC", Sequence = 1, MatchStatus = ((int)MatchStatus.InRunning).ToString() }; Fixture update = new Fixture { Id = "ABC", Sequence = 2, MatchStatus = ((int)MatchStatus.MatchOver).ToString(), Epoch = 2, LastEpochChangeReason = new[] { (int)EpochChangeReason.MatchStatus } }; StreamMessage message = new StreamMessage { Content = update }; resource.Setup(x => x.Id).Returns("ABC"); resource.Setup(x => x.Content).Returns(new Summary()); resource.Setup(x => x.MatchStatus).Returns(MatchStatus.InRunning); resource.Setup(x => x.StartStreaming()).Raises(x => x.StreamConnected += null, EventArgs.Empty); resource.SetupSequence(x => x.GetSnapshot()).Returns(FixtureJsonHelper.ToJson(fixture)).Returns(null); // STEP 2: start the listener StreamListener listener = new StreamListener(resource.Object, connector.Object, state.Object, provider,_settings.Object); listener.Start(); listener.IsStreaming.Should().BeTrue(); // STEP 4: send the update containing a wrong sequence number listener.ResourceOnStreamEvent(this, new StreamEventArgs(JsonConvert.SerializeObject(message))); // STEP 5: check that ProcessSnapshot is called only twice (first snapshot and when the fixture is ended, we get another one)! connector.Verify(x => x.Suspend(It.Is<string>(y => y == "ABC"))); connector.Verify(x => x.ProcessSnapshot(It.IsAny<Fixture>(), It.IsAny<bool>()), Times.Once()); resource.Verify(x => x.GetSnapshot(), Times.AtLeast(2), "The StreamListener was supposed to acquire a new snapshot"); listener.IsFixtureEnded.Should().BeFalse(); listener.IsErrored.Should().BeTrue(); }
/// <summary> /// Richiamato quando l'applicazione viene avviata normalmente dall'utente. All'avvio dell'applicazione /// verranno utilizzati altri punti di ingresso per aprire un file specifico, per visualizzare /// risultati di ricerche e così via. /// </summary> /// <param name="e">Dettagli sulla richiesta e il processo di avvio.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Non ripetere l'inizializzazione dell'applicazione se la finestra già dispone di contenuto, // assicurarsi solo che la finestra sia attiva. if (rootFrame == null) { // Creare un frame che agisca da contesto di navigazione e passare alla prima pagina. rootFrame = new Frame(); // Associare il frame a una chiave SuspensionManager. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: modificare questo valore su una dimensione di cache appropriata per l'applicazione. rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Ripristinare lo stato della sessione salvata solo se appropriato. try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Errore durante il ripristino dello stato. // Si presuppone che non esista alcuno stato e continua. } } // Posizionare il frame nella finestra corrente. Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Rimuove l'avvio della navigazione turnstile. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; if (!Settings.Spot) { if (Shop.getProductStatus()) { Settings.Spot = false; } } Settings.AppOpened++; // Quando lo stack di navigazione non viene ripristinato, esegui la navigazione alla prima pagina, // configurando la nuova pagina per passare le informazioni richieste come parametro di // navigazione. if (!Settings.firstLaunch) { if (!rootFrame.Navigate(typeof(Welcome), e.Arguments)) { throw new Exception("Failed to create initial page"); } } else { string arguments = e.Arguments; Settings.comando = arguments; try { string[] argomenti = arguments.Split(','); System.Diagnostics.Debug.WriteLine(arguments); if (argomenti[0] == "st") { //MessageDialog msg = new MessageDialog("CI SONOO " + argomenti[1]); //await msg.ShowAsync(); int idStazione = Convert.ToInt16(argomenti[1]); if (!rootFrame.Navigate(typeof(SectionPage), idStazione)) { throw new Exception("Failed to create initial page"); } } else { if (!rootFrame.Navigate(typeof(HubPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } } catch (NullReferenceException ex) { System.Diagnostics.Debug.WriteLine("ERRORE ARGOMENTI " + ex.ToString()); if (!rootFrame.Navigate(typeof(HubPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } } } // Assicurarsi che la finestra corrente sia attiva. Window.Current.Activate(); }
/// <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="args">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs args) { 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); //TEALIUM: example for initializing the Tealium Tagger TealiumTagger.Initialize(new TealiumSettings( "tealiummobile", //Tealium account name "win", //Tealium profile name #if DEBUG TealiumEnvironment.TealiumTargetDev //Run against the Dev environment when in "DEBUG" configuration #else TealiumEnvironment.TealiumTargetProd //Run against the Prod environment when in "RELEASE" configuration #endif , new Dictionary <string, object>() { { "SampleGlobalVar1", "test-global" }, { "ScreenOrientation", Windows.Graphics.Display.DisplayProperties.CurrentOrientation.ToString() } } )); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } //TEALIUM: track the current screen orientation as a global variable... Windows.Graphics.Display.DisplayProperties.OrientationChanged += DisplayProperties_OrientationChanged; // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups")) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
private void EnsureWindow(IActivatedEventArgs args) { // No matter what our destination is, we're going to need control data loaded - let's knock that out now. // We'll never need to do this again. //await ControlInfoDataSource.Instance.GetGroupsAsync(); var runGetGroupsSyncTask = Task.Run(async() => { await ControlInfoDataSource.Instance.GetGroupsAsync(); }); runGetGroupsSyncTask.Wait(); XboxGameBarUIExtensionActivatedEventArgs uiExtArgs = null; Frame rootFrame = GetRootFrame(); ThemeHelper.Initialize(); Type targetPageType = typeof(NewControlsPage); string targetPageArguments = string.Empty; if (args.Kind == ActivationKind.Launch) { if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { try { //await SuspensionManager.RestoreAsync(); var runRestoreSyncTask = Task.Run(async() => { await SuspensionManager.RestoreAsync(); }); runRestoreSyncTask.Wait(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } targetPageArguments = ((LaunchActivatedEventArgs)args).Arguments; } else if (args.Kind == ActivationKind.Protocol) { var protocolArgs = args as IProtocolActivatedEventArgs; string protocolString = protocolArgs.Uri.AbsoluteUri; if (protocolString.StartsWith("ms-gamebaruiextension")) { uiExtArgs = args as XboxGameBarUIExtensionActivatedEventArgs; } if (uiExtArgs != null) { //Window.Current.Content = rootFrame; // Navigate to correct view if (uiExtArgs.AppExtensionId == "Extension1") { m_uiExtension1 = new XboxGameBarUIExtension( uiExtArgs, Window.Current.CoreWindow, rootFrame); CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = false; } else { // Unknown - Game Bar should never send you an unknown App Extension Id return; } targetPageArguments = string.Empty; } else { Match match; string targetId = string.Empty; switch (((ProtocolActivatedEventArgs)args).Uri?.AbsolutePath) { case string s when IsMatching(s, "/category/(.*)"): targetId = match.Groups[1]?.ToString(); if (ControlInfoDataSource.Instance.Groups.Any(g => g.UniqueId == targetId)) { targetPageType = typeof(SectionPage); } break; case string s when IsMatching(s, "/item/(.*)"): targetId = match.Groups[1]?.ToString(); if (ControlInfoDataSource.Instance.Groups.Any(g => g.Items.Any(i => i.UniqueId == targetId))) { targetPageType = typeof(ItemPage); } break; } targetPageArguments = targetId; bool IsMatching(string parent, string expression) { match = Regex.Match(parent, expression); return(match.Success); } } } rootFrame.Navigate(targetPageType, targetPageArguments); //((Microsoft.UI.Xaml.Controls.NavigationViewItem)(((NavigationRootPage)(Window.Current.Content)).NavigationView.MenuItems[0])).IsSelected = true; // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </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; } #endif 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; await ApplicationData.Current.SetVersionAsync(0, SetVersionHandler); FavoritesDataSource favoritesDataSource = (FavoritesDataSource)App.Current.Resources["favoritesDataSource"]; if (favoritesDataSource != null) { if (favoritesDataSource.Favorites.Count == 0) { favoritesDataSource.GetFavorites(); } } PrivateKeysDataSource privateKeysDataSource = (PrivateKeysDataSource)App.Current.Resources["privateKeysDataSource"]; if (privateKeysDataSource != null) { if (privateKeysDataSource.PrivateKeys.Count == 0) { await privateKeysDataSource.GetPrivateKeys(); } } ColorThemesDataSource colorThemesDataSource = (ColorThemesDataSource)App.Current.Resources["colorThemesDataSource"]; if (colorThemesDataSource != null) { if (colorThemesDataSource.CustomTheme == null) { colorThemesDataSource.GetColorThemes(); } } if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(FavoritesPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
/// <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="args">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs args) { 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) { var licenseInformation = CurrentApp.LicenseInformation; //await LibrelioApplication.Utils.Utils.prepareTestData(); SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested; var fileHandle = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"CustomizationAssets\application_.xml"); var xml = await XmlDocument.LoadFromFileAsync(fileHandle); var appName = xml.SelectSingleNode("/resources/string[@name='app_name']"); ClientName = xml.SelectSingleNode("/resources/string[@name='client_name']").InnerText; MagazineName = xml.SelectSingleNode("/resources/string[@name='magazine_name']").InnerText; SharingTitle = xml.SelectSingleNode("/resources/string[@name='sharing_title']").InnerText; SharingText = xml.SelectSingleNode("/resources/string[@name='sharing_text']").InnerText; SharingLink = xml.SelectSingleNode("/resources/string[@name='sharing_link']").InnerText; PrivacyLink = xml.SelectSingleNode("/resources/string[@name='privacy_link']").InnerText; var node = xml.SelectSingleNode("/resources/hex[@name='background_color']"); Color = node.InnerText; SetupCustomColors(); Application.Current.Resources["AppName"] = appName.InnerText; Manager = new MagazineManager("http://librelio-europe.s3.amazonaws.com/" + ClientName + "/" + MagazineName + "/", "Magazines"); await DiscoverActiveDownloadsAsync(); // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(LibrelioApplication.ItemsPage), "AllGroups")) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
// Token: 0x06000AF7 RID: 2807 RVA: 0x0000A919 File Offset: 0x00008B19 public new void Awake() { base.Awake(); SuspensionManager.Register(this); this.m_transform = base.transform; }
private void Page_Loaded(object sender, RoutedEventArgs e) { try { // Jump to the page item if this is a back button action if (this.Frame.CanGoForward) { var frameState = SuspensionManager.SessionStateForFrame(this.Frame); var lastPageParameters = frameState["Page-" + (this.Frame.BackStackDepth + 1)] as IDictionary <string, object>; var index = (int)lastPageParameters["Index"]; var postId = (int)lastPageParameters["PostId"]; if (this.HomeViewModel.SelectedViewIndex == 0) { // Pre-fall creator has different image loading order // unable to share same connected animation code without breaking the UI if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5)) { var post = FeatureView.FeatureViewModel.TopToday.First(o => o.Id == postId); if (post != null && FeatureView.FeatureViewModel.TopToday.IndexOf(post) != -1) { // Start the animation ConnectedAnimation animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("PreviewImage"); if (animation != null) { FeatureView.UpdateLayout(); animation.TryStart(this.FeatureView.GetTopTodayButton(FeatureView.FeatureViewModel.TopToday.IndexOf(post))); } } } } else if (this.HomeViewModel.SelectedViewIndex == 1 || this.HomeViewModel.SelectedViewIndex == 2) { JustifiedWrapPanel panel = null; if (this.HomeViewModel.SelectedViewIndex == 1) { // Navigating back from a search result image panel = BrowsePanel; } else if (this.HomeViewModel.SelectedViewIndex == 2) { // Navigating back from a favorite image panel = FavoritePanel; } // Scroll into the index of last opened page panel.ScrollIntoView((panel.ItemsSource as IList)[index], ScrollIntoViewAlignment.Default); panel.UpdateLayout(); // Pre-fall creator has different image loading order // unable to share same connected animation code without breaking the UI if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5)) { // Start the animation ConnectedAnimation animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("PreviewImage"); if (animation != null) { if (panel.ContainerFromIndex(index) is ContentControl container) { var root = (FrameworkElement)container.ContentTemplateRoot; var image = (UIElement)root.FindName("PreviewImage"); animation.TryStart(image); } } } } } } catch (Exception ex) { } }
// Token: 0x06001409 RID: 5129 RVA: 0x00002AB0 File Offset: 0x00000CB0 public void Awake() { SuspensionManager.Register(this); }
private async void ExtendedSplashScreen_Loaded(object sender, RoutedEventArgs e) { ProgressText.Text = ApplicationData.Current.LocalSettings.Values.ContainsKey("Initialized") && (bool)ApplicationData.Current.LocalSettings.Values["Initialized"] ? "Loading blogs..." : "Initializing for first use: this may take several minutes..."; await App.Instance.DataSource.LoadGroups(); foreach (var group in App.Instance.DataSource.GroupList) { Progress.IsActive = true; ProgressText.Text = "Loading " + group.Title; await App.Instance.DataSource.LoadAllItems(group); } ApplicationData.Current.LocalSettings.Values["Initialized"] = true; // Create a Frame to act as the navigation context and associate it with // a SuspensionManager key var rootFrame = new Frame(); SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); var list = App.Instance.DataSource.GroupList; var totalNew = list.Sum(g => g.NewItemCount); if (totalNew > 99) { totalNew = 99; } if (totalNew > 0) { var badgeContent = new BadgeNumericNotificationContent((uint)totalNew); BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification()); } else { BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear(); } // load most recent 5 items then order from oldest to newest var query = from i in (from g in list from i in g.Items orderby i.PostDate descending select i).Take(5) orderby i.PostDate select i; var x = 0; var notificationCount = totalNew; TileUpdateManager.CreateTileUpdaterForApplication().Clear(); TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); foreach (var item in query) { var squareTile = new TileSquarePeekImageAndText04(); squareTile.TextBodyWrap.Text = item.Title; squareTile.Image.Alt = item.Title; squareTile.Image.Src = item.DefaultImageUri.ToString(); var wideTile = new TileWideSmallImageAndText03 { SquareContent = squareTile }; wideTile.Image.Alt = item.Title; wideTile.Image.Src = item.DefaultImageUri.ToString(); wideTile.TextBodyWrap.Text = item.Title; var notification = wideTile.CreateNotification(); notification.Tag = string.Format("Item {0}", x++); TileUpdateManager.CreateTileUpdaterForApplication().Update(notification); // send a notification if (notificationCount-- <= 0) { continue; } var notifier = ToastNotificationManager.CreateToastNotifier(); if (notifier.Setting == NotificationSetting.Enabled) { // send a toast notification var notificationTemplate = ToastContentFactory.CreateToastImageAndText02(); notificationTemplate.Launch = string.Format("Item={0}", item.Id); notificationTemplate.TextHeading.Text = item.Group.Title; notificationTemplate.TextBodyWrap.Text = item.Title; notificationTemplate.Image.Src = item.DefaultImageUri.ToString(); notificationTemplate.Image.Alt = item.Title; var toast = notificationTemplate.CreateNotification(); var date = DateTimeOffset.Now.AddSeconds(30); var scheduledToast = new ScheduledToastNotification(toast.Content, date); notifier.AddToSchedule(scheduledToast); } } if (_activationArgs.Arguments.StartsWith("Group")) { var group = _activationArgs.Arguments.Split('='); rootFrame.Navigate(typeof(GroupDetailPage), group[1]); } else if (_activationArgs.Arguments.StartsWith("Item")) { var item = _activationArgs.Arguments.Split('='); rootFrame.Navigate(typeof(ItemDetailPage), item[1]); } else if (_activationArgs.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate await SuspensionManager.RestoreAsync(); } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups")) { throw new Exception("Failed to create initial page"); } } // Place the frame in the current Window and ensure that it is active Window.Current.Content = rootFrame; Window.Current.Activate(); }
/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); await SuspensionManager.SaveAsync(); deferral.Complete(); }
/// <summary> /// Chamado quando o aplicativo é iniciado normalmente pelo usuário final. Outros pontos de entrada /// serão usados quando o aplicativo é iniciado para abrir um arquivo específico, para exibir /// resultados da pesquisa e assim por diante. /// </summary> /// <param name="e">Detalhes sobre a solicitação e o processo de inicialização.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Não repita a inicialização do aplicativo quando a Janela já tiver conteúdo, // apenas verifique se a janela está ativa. if (rootFrame == null) { // Crie um Quadro para atuar como o contexto de navegação e navegue para a primeira página. rootFrame = new Frame(); // Associe o quadro a uma chave SuspensionManager. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: Altere este valor para um tamanho de cache apropriado para seu aplicativo. rootFrame.CacheSize = 1; // Definir o idioma padrão rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restaure o estado de sessão salvo somente quando apropriado. try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Erro ao restaurar o estado. // Vamos supor que não há estado e continuar. } } // Coloque o quadro na Janela atual. Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { //Remove a animação turnstile na inicialização. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // Quando a pilha de navegação não for restaurada, navegar para a primeira página, // configurando a nova página passando as informações necessárias como um parâmetro // parâmetro. if (!rootFrame.Navigate(typeof(PivotPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Verifique se a janela atual está ativa. Window.Current.Activate(); }
/// <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 override async void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = null; //#if DEBUG // if (System.Diagnostics.Debugger.IsAttached) // { // this.DebugSettings.EnableFrameRateCounter = true; // } //#endif #if !WINDOWS_PHONE_APP FrameworkElement shell = Window.Current.Content as FrameworkElement; if (shell == null) { DefaultContentLoader contentLoader = this.resolver.Get <DefaultContentLoader>(); shell = (FrameworkElement)contentLoader.LoadContent(new Uri("/", UriKind.RelativeOrAbsolute)); } rootFrame = (Frame)shell.FindName("rootFrame"); if (rootFrame != null) { // Load the app name resource into the app's resource dictionary. ResourceLoader resourceLoader = new ResourceLoader(); var appName = resourceLoader.GetString("appName"); if (String.IsNullOrEmpty(appName)) { appName = "App name"; } App.Current.Resources.Remove("AppName"); App.Current.Resources.Add("AppName", appName); // Associate the frame with a SuspensionManager key. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } // Place the main page in the current Window. Window.Current.Content = shell; if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(LobbyView), e.Arguments); } } else { throw new Exception("Root frame was not found."); } #endif // left here to serve as documentation when wp is supported. if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif } // Ensure the current window is active Window.Current.Activate(); }
private async Task EnsureWindow(IActivatedEventArgs args) { // No matter what our destination is, we're going to need control data loaded - let's knock that out now. // We'll never need to do this again. await NavigationInfoDataSource.Instance.GetItemsAsync(); Frame rootFrame = GetRootFrame(); string savedTheme = ApplicationData.Current.LocalSettings.Values[SelectedAppThemeKey]?.ToString(); if (savedTheme != null) { RootTheme = GetEnum <ElementTheme>(savedTheme); } Type targetPageType = typeof(HomePage); string targetPageArguments = string.Empty; if (args.Kind == ActivationKind.Launch) { if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } targetPageArguments = ((LaunchActivatedEventArgs)args).Arguments; } else if (args.Kind == ActivationKind.Protocol) { Match match; string targetId = string.Empty; switch (((ProtocolActivatedEventArgs)args).Uri?.AbsolutePath) { //case string s when IsMatching(s, "/category/(.*)"): // targetId = match.Groups[1]?.ToString(); // if (NavigationInfoDataSource.Instance.Items.Any(i => i.UniqueId == targetId)) // { // //targetPageType = typeof(SectionPage); // } // break; case string s when IsMatching(s, "/item/(.*)"): targetId = match.Groups[1]?.ToString(); if (NavigationInfoDataSource.Instance.Items.Any(i => i.UniqueId == targetId)) { targetPageType = typeof(ItemPage); } break; } targetPageArguments = targetId; bool IsMatching(string parent, string expression) { match = Regex.Match(parent, expression); return(match.Success); } } rootFrame.Navigate(targetPageType, targetPageArguments); #region Draw into the title bar var coreTitleBar = Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar; coreTitleBar.ExtendViewIntoTitleBar = this.Extend; if (this.Extend) { // remove the solid-colored backgrounds behind the caption controls and system back button var titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; titleBar.ButtonForegroundColor = (Color)Resources["SystemBaseHighColor"]; Window.Current.CoreWindow.SizeChanged += (s, e) => UpdateAppTitle(); coreTitleBar.LayoutMetricsChanged += (s, e) => UpdateAppTitle(); } else { // Darken the window title bar using a color value to match app theme var titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar; if (titleBar != null) { Color titleBarColor = (Color)App.Current.Resources["SystemChromeMediumColor"]; //var titleBarColor = Colors.Bisque; titleBar.BackgroundColor = titleBarColor; titleBar.ButtonBackgroundColor = titleBarColor; } } #endregion //// Ensure the current window is active Window.Current.Activate(); }
private async Task ShowWindow(LaunchActivatedEventArgs e) { //获取并记录屏幕宽度,一定要在程序启动的时候记录,这样记录到的数据才是竖屏下的屏幕高度。屏幕旋转Window.Current.Bounds.With宽高会互换 AppEnvironment.ScreenPortraitWith = Window.Current.Bounds.Width; //初始化MvvmLight线程 GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize(); NavigationRootPage rootPage = Window.Current.Content as NavigationRootPage; Frame rootFrame = null; // 不要在窗口已包含内容时重复应用程序初始化, // 只需确保窗口处于活动状态 if (rootPage == null) { // 创建要充当导航上下文的框架,并导航到第一页 rootPage = new NavigationRootPage(); rootFrame = (Frame)rootPage.FindName("rootFrame"); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: 从之前挂起的应用程序加载状态 try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } //如果是手机,则默认全屏模式 if (AppEnvironment.IsPhone) { ApplicationView.GetForCurrentView().TryEnterFullScreenMode(); //ApplicationView.GetForCurrentView().TitleBar } else { // DisplayProperties.CurrentOrientation 发生变化时触发的事件 //设置平板窗口的最小宽高 ApplicationView.GetForCurrentView().SetPreferredMinSize(AppEnvironment.DesktopSize); } //初始化数据库 await InitDatabase(); //获取数据库数据 await GetDatabaseCollection(); //处理自定义SplashScreenImage var isLoadSplashImageSuccess = await InitSplashScreenImage(); //如果SplashScreenI加载失败,则不显示欢迎屏幕,直接进入主界面 if (isLoadSplashImageSuccess) { //存储第一次启动的表示,是为了防止DailyPage第一页加载数据的时候把ProgressUIControl或者RetryUIControl显示出来,达到正确显示的逻辑处理 DicStore.AddOrUpdateValue <bool>(AppCommonConst.IS_APP_FIRST_LAUNCH, true); //这句话放在Activate()之前是为了保证在系统的初始屏幕SplashScreen.png消失之后能够显示ShowWelcome的内容。这是正确的处理逻辑 WelcomeBox.Instance.ShowWelcome(); } //这句话调用以后,在Package.appxmanifest文件配置的初始屏幕SplashScreen.png就会消失。不写这句话的话,会一直停留显示在初始屏幕SplashScreen.png处。因此,自定义SplashScreenImage的处理逻辑应该放在这句话之前 //确保当前窗口处于活动状态 Window.Current.Activate(); //这个放在Activate()方法下面是为了防止在ShowWelcome没显示之前Window.Current.Content就显示出来的问题。因为只要写了这句话,rootPage就会立刻被激活显示,此时的ShowWelcome可能还没显示出来,造成闪一下的问题。放在ShowWelcome()和Activate()之后才是正确的处理逻辑。 // 将框架放在当前窗口中 Window.Current.Content = rootPage; } if (rootFrame != null && rootFrame.Content == null) { // 当导航堆栈尚未还原时,导航到第一页, // 并通过将所需信息作为导航参数传入来配置 // 参数 rootFrame.Navigate(typeof(DailyPage), "每日精选"); } Window.Current.Activate(); }
/// <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 = false; } #endif #region ScheduledTask var scheduledTaskRegistered = BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == "KursnaLista.Tasks.ScheduledTask"); if (!scheduledTaskRegistered) { #if WINDOWS_PHONE_APP await BackgroundExecutionManager.RequestAccessAsync(); #endif var builder = new BackgroundTaskBuilder(); builder.Name = "ScheduledTask"; builder.TaskEntryPoint = "KursnaLista.Tasks.ScheduledTask"; builder.SetTrigger(new TimeTrigger(15, false)); builder.Register(); } #endregion 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } ViewModelLocator.NavigationService.Frame = rootFrame; if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } 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 if (!ViewModelLocator.NavigationService.NavigateTo <IMainPageView>()) { throw new Exception("Failed to create initial page"); } } if (!string.IsNullOrEmpty(e.Arguments)) { var fromTo = e.Arguments.Split(':'); if (!ViewModelLocator.NavigationService.NavigateTo <IConverterPageView>(new { From = fromTo[0], To = fromTo[1] }, ViewModelLocator.NavigationService.Frame.Content is IConverterPageView)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters this.DebugSettings.EnableFrameRateCounter = true; } #endif 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) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } KinectRegion kinectRegion = new KinectRegion(); KinectUserViewer kinectUserViewer = new KinectUserViewer() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top, Height = 100, Width = 121 }; Grid grid = new Grid(); grid.Children.Add(kinectRegion); grid.Children.Add(kinectUserViewer); kinectRegion.Content = rootFrame; // Place the frame in the current Window Window.Current.Content = grid; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(GroupedItemsPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
public void SuspensionManagerStrategiesTest() { var stateProvider = new Mock<IStateProvider>(); var plugin = new Mock<IAdapterPlugin>(); var suspensionManager = new SuspensionManager(stateProvider.Object, plugin.Object); var state = new MarketStateCollection("FXT-ID"); // STEP 1: prepare the fixture // 1) fixture is in running // 2) with 2 in play markets // 3) 1 not in-play market // 4) 3 markets with an unknown state Fixture fixture = new Fixture { Id = "FXT-ID", MatchStatus = MatchStatus.InRunning.ToString(), Sequence = 2 }; var mkt1 = new Market { Id = "MKT-1" }; mkt1.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Active }); var mkt2 = new Market { Id = "MKT-2" }; mkt2.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Active }); var mkt3 = new Market { Id = "MKT-3" }; mkt3.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Pending }); var mkt4 = new Market { Id = "MKT-4" }; mkt4.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Active }); mkt4.AddOrUpdateTagValue("traded_in_play", "false"); var mkt5 = new Market { Id = "MKT-5" }; mkt5.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Active }); mkt5.AddOrUpdateTagValue("traded_in_play", "true"); var mkt6 = new Market { Id = "MKT-6" }; mkt6.AddOrUpdateTagValue("traded_in_play", "true"); fixture.Markets.Add(mkt1); fixture.Markets.Add(mkt2); fixture.Markets.Add(mkt3); fixture.Markets.Add(mkt4); fixture.Markets.Add(mkt5); fixture.Markets.Add(mkt6); state.Update(fixture, true); state.CommitChanges(); // STEP 2: test the suspension strategies suspensionManager.SuspendAllMarketsStrategy(state); plugin.Verify(x => x.ProcessStreamUpdate(It.Is<Fixture> ( y => y.Markets.Count == 6 && y.Markets.FirstOrDefault(z => z.Id == "MKT-1") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-2") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-3") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-4") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-5") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-6") != null ), It.IsAny<bool>())); suspensionManager.SuspendFixtureIfInPlayStrategy(state); plugin.Verify(x => x.Suspend(It.Is<string>(y => y == "FXT-ID"))); suspensionManager.SuspendFixtureStrategy(state); plugin.Verify(x => x.Suspend(It.Is<string>(y => y == "FXT-ID"))); suspensionManager.SuspendInPlayMarketsStrategy(state); // The SuspensionManager takes a conservative approach. // If the traded_in_play tag is not present, it assumes // that the market is a in-play market plugin.Verify(x => x.ProcessStreamUpdate(It.Is<Fixture> ( y => y.Markets.Count == 3 && y.Markets.FirstOrDefault(z => z.Id == "MKT-1") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-2") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-3") == null && y.Markets.FirstOrDefault(z => z.Id == "MKT-4") == null && y.Markets.FirstOrDefault(z => z.Id == "MKT-5") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-6") == null ), It.IsAny<bool>())); // STEP 3: change the fixture // 1) change the fixture's match status // 2) remove a mkt // 3) add a new mkt fixture.MatchStatus = MatchStatus.MatchOver.ToString(); fixture.Markets.Remove(fixture.Markets.FirstOrDefault(x => x.Id == "MKT-5")); var mkt7 = new Market { Id = "MKT-7" }; mkt7.Selections.Add(new Selection { Id = "SELN", Status = SelectionStatus.Active }); mkt7.AddOrUpdateTagValue("traded_in_play", "true"); fixture.Markets.Add(mkt7); state.Update(fixture, true); state.CommitChanges(); // STEP 4: test the suspension strategies again suspensionManager.SuspendAllMarketsStrategy(state); // note that we must have 7 markets now because the // SuspensionManager looks at the MarketState, not // at the fixture plugin.Verify(x => x.ProcessStreamUpdate(It.Is<Fixture> ( y => y.Markets.Count == 7 && y.Markets.FirstOrDefault(z => z.Id == "MKT-1") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-2") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-3") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-4") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-5") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-6") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-7") != null ), It.IsAny<bool>())); suspensionManager.SuspendFixtureIfInPlayStrategy(state); // The fixture is "MatchOver", so the Suspend() method should not have been called // Times.Exactly(2) because it has been called in the previous step...unfortunately // there seems to be no way to reset the verifications plugin.Verify(x => x.Suspend(It.Is<string>(y => y == "FXT-ID")), Times.Exactly(2)); suspensionManager.SuspendFixtureStrategy(state); plugin.Verify(x => x.Suspend(It.Is<string>(y => y == "FXT-ID")), Times.Exactly(3)); suspensionManager.SuspendInPlayMarketsStrategy(state); plugin.Verify(x => x.ProcessStreamUpdate(It.Is<Fixture> ( y => y.Markets.Count == 4 && y.Markets.FirstOrDefault(z => z.Id == "MKT-1") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-2") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-3") == null && y.Markets.FirstOrDefault(z => z.Id == "MKT-4") == null && y.Markets.FirstOrDefault(z => z.Id == "MKT-5") != null && y.Markets.FirstOrDefault(z => z.Id == "MKT-6") == null && y.Markets.FirstOrDefault(z => z.Id == "MKT-7") != null ), It.IsAny<bool>())); }