/// <summary> /// Implements and seals the OnInitialize method to configure the container. /// </summary> /// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param> protected override Task OnInitializeAsync(IActivatedEventArgs args) { ConfigureContainer(); ConfigureViewModelLocator(); return Task.FromResult<object>(null); }
protected async override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); var continuationEventArgs = args as IContinuationActivatedEventArgs; if (continuationEventArgs != null) { switch (continuationEventArgs.Kind) { case ActivationKind.PickFileContinuation: FileOpenPickerContinuationEventArgs arguments = continuationEventArgs as FileOpenPickerContinuationEventArgs; StorageFile file = arguments.Files.FirstOrDefault(); var messenger = Mvx.Resolve<IMvxMessenger>(); using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { var buffer = new byte[imgStream.Size]; await imgStream.ReadAsync(buffer.AsBuffer(), (uint)imgStream.Size, InputStreamOptions.None); var properties = await file.Properties.GetImagePropertiesAsync(); var message = new PictureMessage(this) { Width = properties.Width, Height = properties.Height, Picture = buffer }; messenger.Publish(message); } break; } } }
protected override void OnActivated(IActivatedEventArgs e) { var rootFrame = BuildRootFrame(e.PreviousExecutionState); if (e.Kind == ActivationKind.Protocol) { var protocolArgs = e as ProtocolActivatedEventArgs; var uri = protocolArgs.Uri; var scheme = uri.Scheme; if (scheme == "weburl") { rootFrame.Navigate(typeof (Player), uri); } else { BuildRootContent(rootFrame, null); } } #if WINDOWS_PHONE_APP else if (e is IContinuationActivatedEventArgs) { continuationManager = new ContinuationManager(); var continuationEventArgs = e as IContinuationActivatedEventArgs; continuationManager.Continue(continuationEventArgs, rootFrame); } #endif else { BuildRootContent(rootFrame, null); } Window.Current.Activate(); }
// *** Methods *** public async Task<bool> Activate(IActivatedEventArgs activatedEventArgs) { // Raise Activating event EventHandler<IActivatedEventArgs> activatingEventHandler = Activating; if (activatingEventHandler != null) activatingEventHandler(this, activatedEventArgs); // Call activate on all activation handlers // NB: We convert to an array so that the Select is not called multiple times IEnumerable<Task<bool>> activationTasks = registeredServices.Select(service => service.Activate(activatedEventArgs)).ToArray(); await Task.WhenAll(activationTasks); // Raise Activated event EventHandler<IActivatedEventArgs> activatedEventHandler = Activated; if (activatedEventHandler != null) activatedEventHandler(this, activatedEventArgs); // Determine if the activation was handled by any of the handlers Task<bool> firstHandlingTask = activationTasks.FirstOrDefault(task => task.Result == true); bool handled = firstHandlingTask != null; // If the activation was handled then activate the current window if (handled && Window.Current != null) Window.Current.Activate(); return handled; }
// runs even if restored from state public override async Task OnInitializeAsync(IActivatedEventArgs args) { // setup hamburger shell var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); Window.Current.Content = new Views.Shell(nav); await Task.Yield(); }
// runs even if restored from state public override Task OnInitializeAsync(IActivatedEventArgs args) { // setup hamburger shell var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); Window.Current.Content = new Views.Shell(nav); return Task.FromResult<object>(null); }
protected override void OnActivated(IActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } switch (args.Kind) { case ActivationKind.VoiceCommand: HandleVoiceCommand(args, rootFrame); break; default: break; } Window.Current.Activate(); base.OnActivated(args); }
protected override Task OnInitializeAsync(IActivatedEventArgs args) { Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader())); ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) => { var viewName = viewType.FullName; if (viewName.Contains(".Views.")) { viewName = viewName.Replace(".Views.", ".PageViewModels."); } else { throw new ArgumentException($"The specified View type {viewName} isn't in the Views namespace."); } //// TODO: Uncomment this if ViewModels are in a separate project ////var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName.Replace("$safeprojectname$", "$safeprojectname$.ViewModel"); var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName; var suffix = viewName.EndsWith("View") ? "Model" : "ViewModel"; var viewModelName = StringHelper.InvariantCulture($"{viewName}{suffix}, {viewAssemblyName}"); return Type.GetType(viewModelName); }); return base.OnInitializeAsync(args); }
protected override void OnActivated(IActivatedEventArgs e) { if (e.Kind == ActivationKind.Protocol) { var protocolArgs = e as ProtocolActivatedEventArgs; var uri = protocolArgs.Uri; if (uri.AbsoluteUri.IndexOf("?access_token=") != -1) { int Start = uri.AbsoluteUri.IndexOf("?access_token="); int offset = ("?access_token=").Length; int End = uri.AbsoluteUri.IndexOf("&expires_in"); string FBtoken = uri.AbsoluteUri.Substring(Start + offset, End - Start - offset); if (OnProtocolActivated != null) OnProtocolActivated.Invoke(this, FBtoken); } else { SocialAuthentication.RaiseAuthenFail(); } return; } base.OnActivated(e); }
////======================================================================================================= /// <summary> /// /// </summary> /// <param name="args"></param> /// <returns></returns> ////======================================================================================================= protected override Task OnInitializeAsync(IActivatedEventArgs args) { //ViewModelLocationProvider.Register(typeof(MainPage).ToString(), () => new MainPageViewModel(NavigationService)); //ViewModelLocationProvider.Register(typeof(UserInput this.RegisterTypes(); return base.OnInitializeAsync(args); }
protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { OnProtocolActivated((ProtocolActivatedEventArgs)args); } }
protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.ProtocolForResults) { ShowPage(typeof(ProtocolPage), args); } }
protected override void OnActivated(IActivatedEventArgs args) { var rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { base.OnActivated(args); return; } // Return to Reply Page with image. var replyPage = rootFrame.Content as ReplyPage; if (replyPage != null && args is FileOpenPickerContinuationEventArgs) { replyPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs); } var editPage = rootFrame.Content as EditPage; if (editPage != null && args is FileOpenPickerContinuationEventArgs) { editPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs); } // Voice command!111!!!11! if (args.Kind == ActivationKind.VoiceCommand) { VoiceCommandActivatedEventArgs vcArgs = (VoiceCommandActivatedEventArgs) args; string voiceCommandName = vcArgs.Result.RulePath.First(); rootFrame.Navigate(typeof(VoiceHandlePage), vcArgs.Result); } base.OnActivated(args); }
void Activate(IActivatedEventArgs e) { switch (e.Kind) { case ActivationKind.Launch: { var args = e as ILaunchActivatedEventArgs; if (args.PreviousExecutionState == ApplicationExecutionState.Running) this.Frame.Navigate(typeof(Views.Splash)); else { // do not activate, let the splash activate itself var page = new Views.Splash() { SplashScreen = args.SplashScreen, Navigate = () => this.Frame.Navigate(typeof(Views.MainPage)) }; Window.Current.Content = page as UIElement; page.Start(); } break; } default: throw new NotImplementedException(e.Kind.ToString()); } }
/// <summary> /// Invoked when application is launched through protocol. /// Read more - http://msdn.microsoft.com/library/windows/apps/br224742 /// </summary> /// <param name="args"></param> protected override void OnActivated(IActivatedEventArgs args) { string appArgs = ""; switch (args.Kind) { case ActivationKind.Protocol: ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs; splashScreen = eventArgs.SplashScreen; appArgs += string.Format("Uri={0}", eventArgs.Uri.AbsoluteUri); break; case ActivationKind.VoiceCommand: var commandArgs = args as VoiceCommandActivatedEventArgs; SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; string voiceCommandName = speechRecognitionResult.RulePath[0]; // This is one way of handling different commands found in the VCD file with code. switch (voiceCommandName) { case "startPlay": { break; } case "checkScore": if (speechRecognitionResult.SemanticInterpretation.Properties.ContainsKey("message")) { // Just to show you can get the message as well.. string message = speechRecognitionResult.SemanticInterpretation.Properties["message"][0]; } break; } break; } InitializeUnity(appArgs); }
// runs even if restored from state public override Task OnInitializeAsync(IActivatedEventArgs args) { var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); 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(); //rootFrame.NavigationFailed += OnNavigationFailed; // 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(Views.MainPage), null); } // Ensure the current window is active Window.Current.Activate(); //Window.Current.Content = new Views.Shell(nav); //Window.Current.Content = new Views.MainPage(); return Task.FromResult<object>(null); }
protected override void OnActivated(IActivatedEventArgs args) { InitializeApp(); // Was the app activated by a voice command? if (args.Kind == Windows.ApplicationModel.Activation.ActivationKind.VoiceCommand) { var commandArgs = args as Windows.ApplicationModel.Activation.VoiceCommandActivatedEventArgs; Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; // If so, get the name of the voice command and the values for the semantic properties from the grammar file string voiceCommandName = speechRecognitionResult.RulePath[0]; var interpretation = speechRecognitionResult.SemanticInterpretation.Properties; IReadOnlyList<string> dictatedSearchTerms; interpretation.TryGetValue("dictatedSearchTerms", out dictatedSearchTerms); switch (voiceCommandName) { case "NearMeSearch": MainViewModel.SearchNearMeCommand.Execute(null); break; case "PlaceSearch": MainViewModel.SearchTerm = dictatedSearchTerms[0]; MainViewModel.SearchTrailsCommand.Execute(null); break; default: // There is no match for the voice command name. break; } } }
public static void Init (IActivatedEventArgs launchActivatedEventArgs) { if (s_isInitialized) return; var accent = (SolidColorBrush)Windows.UI.Xaml.Application.Current.Resources["SystemColorControlAccentBrush"]; Color.Accent = Color.FromRgba (accent.Color.R, accent.Color.G, accent.Color.B, accent.Color.A); Log.Listeners.Add (new DelegateLogListener ((c, m) => Debug.WriteLine (LogFormat, c, m))); Windows.UI.Xaml.Application.Current.Resources.MergedDictionaries.Add (GetPhoneResources()); Device.OS = TargetPlatform.Windows; Device.PlatformServices = new WindowsPhonePlatformServices (Window.Current.Dispatcher); Device.Info = new WindowsDeviceInfo(); Device.Idiom = TargetIdiom.Phone; Ticker.Default = new WindowsTicker(); ExpressionSearch.Default = new WindowsExpressionSearch(); Registrar.RegisterAll (new[] { typeof (ExportRendererAttribute), typeof (ExportCellAttribute), typeof (ExportImageSourceHandlerAttribute) }); MessagingCenter.Subscribe<Page, bool> (Device.PlatformServices, Page.BusySetSignalName, OnPageBusy); HardwareButtons.BackPressed += OnBackPressed; s_isInitialized = true; s_state = launchActivatedEventArgs.PreviousExecutionState; }
private async void App_Activated(object sender, IActivatedEventArgs e) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate { if (e.Kind != ActivationKind.ToastNotification) return; var toastArgs = e as ToastNotificationActivatedEventArgs; if (toastArgs == null) { Error("Activation args was not of type ToastNotificationActivatedEventArgs"); return; } string arguments = toastArgs.Argument; if (arguments == null || !arguments.Equals("quickReply")) { Error($"Expected arguments to be 'quickReply' but was '{arguments}'. User input values...\n{ToastHelper.ToString(toastArgs.UserInput)}"); return; } switch (stepsControl.Step) { case 1: validateStep1(toastArgs.UserInput); break; } }); }
protected override void OnActivated(IActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } string uri = string.Empty; var protocolArgs = args as ProtocolActivatedEventArgs; if(protocolArgs != null) { uri = protocolArgs.Uri.ToString(); } rootFrame.Navigate(typeof(ProtocolActivationPage), uri); // Ensure the current window is active Window.Current.Activate(); }
protected override void OnActivated(IActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; rootFrame = (rootFrame.Content as MainPage).WorkflowFrame; if (args.Kind == ActivationKind.VoiceCommand) { var commandArgs = args as VoiceCommandActivatedEventArgs; SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; string voiceCommandName = speechRecognitionResult.RulePath[0]; switch (voiceCommandName) { case "recordConsent": rootFrame.Navigate(typeof(RecordConsent), "Record"); break; case "stopConsent": rootFrame.Navigate(typeof(RecordConsent), "Stop"); break; case "patientStat": rootFrame.Navigate(typeof(HeartRate), "Stat"); break; case "trackEquip": rootFrame.Navigate(typeof(EquipTrack), "Track"); break; case "takeNote": rootFrame.Navigate(typeof(MainPage), "Note"); break; case "checklist": rootFrame.Navigate(typeof(CheckList), "checklist"); break; case "verifyPat": rootFrame.Navigate(typeof(FaceComp), "FaceAPI"); break; } } }
private async Task<bool> ActivateInternal(IActivatedEventArgs activatedEventArgs) { if (activatedEventArgs.Kind == ActivationKind.Search) { ISearchActivatedEventArgs searchEventArgs = (ISearchActivatedEventArgs)activatedEventArgs; // If the previous execution state was terminated then attempt to restore the navigation stack if (activatedEventArgs.PreviousExecutionState == ApplicationExecutionState.Terminated) await _navigationManager.RestoreNavigationStack(); // Otherwise if the application is a new instance navigate to the home page else if (activatedEventArgs.PreviousExecutionState == ApplicationExecutionState.ClosedByUser || activatedEventArgs.PreviousExecutionState == ApplicationExecutionState.NotRunning) _navigationManager.NavigateTo(_navigationManager.HomePageName); // Then display the search results DisplaySearchResults(searchEventArgs.QueryText, searchEventArgs.Language); return true; } return false; }
protected override void OnActivated(IActivatedEventArgs args) { var launchContinuationArgs = args as ProtocolWithResultsContinuationActivatedEventArgs; if (launchContinuationArgs != null) { 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(); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } // Navigate to the continuation page, configuring the new page by passing the // results ValueSet as a navigation parameter rootFrame.Navigate(typeof(ContinuationPage),launchContinuationArgs.Result); // Ensure the current window is active Window.Current.Activate(); } }
protected override async void OnActivated(IActivatedEventArgs e) { switch (e.Kind) { // See http://go.microsoft.com/fwlink/?LinkID=288842 case ActivationKind.Launch: var args = e as LaunchActivatedEventArgs; if (args.TileId == "App" && !args.Arguments.Any()) { await OnActivatedByPrimaryTileAsync(args); } else if (args.TileId == "App" && args.Arguments.Any()) { await OnActivatedBySecondaryTileAsync(args); } else { await OnActivatedByToastNotificationAsync(args); } break; case ActivationKind.Protocol: case ActivationKind.ProtocolForResults: case ActivationKind.ProtocolWithResultsContinuation: await OnActivatedByProtocolAsync(e as ProtocolActivatedEventArgs); break; default: break; } // this is to handle any other type of activation await this.OnActivatedAsync(e); Window.Current.Activate(); }
protected override void OnActivated(IActivatedEventArgs e) { base.OnActivated(e); try { if (e.Kind == ActivationKind.VoiceCommand) { VoiceCommandActivatedEventArgs args = (VoiceCommandActivatedEventArgs)e; Library.Command = args.Result.SemanticInterpretation.Properties["colour"].FirstOrDefault(); } } catch { } Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e); } Window.Current.Activate(); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { GoogleAnalytics.EasyTracker.GetTracker().SendEvent("Lifecycle", startKind.ToString(), null, 0); bool isNewLaunch = args.PreviousExecutionState == ApplicationExecutionState.NotRunning; if (isNewLaunch) { await InitLibrary(); var nav = new MergedNavigationService(NavigationService); nav.Configure(ViewModelLocator.SplashPageKey, typeof(Pages.SplashScreen)); nav.Configure(ViewModelLocator.FrontPageKey, typeof(FrontPage)); nav.Configure(ViewModelLocator.SubGalleryPageKey, typeof(SubGalleryPage)); nav.Configure(ViewModelLocator.SubredditBrowserPageKey, typeof(SubredditBrowserPage)); nav.Configure(ViewModelLocator.BrowserPageKey, typeof(BrowserPage)); if (!SimpleIoc.Default.IsRegistered<GalaSoft.MvvmLight.Views.INavigationService>()) SimpleIoc.Default.Register<GalaSoft.MvvmLight.Views.INavigationService>(() => nav); SimpleIoc.Default.Register<IViewModelLocator>(() => ViewModelLocator.GetInstance()); SimpleIoc.Default.Register<RemoteDeviceHelper>(); } JObject navigationParam = new JObject(); navigationParam["isNewLaunch"] = isNewLaunch; if (args is ProtocolActivatedEventArgs) { var protoArgs = args as ProtocolActivatedEventArgs; if (args.Kind == ActivationKind.Protocol) navigationParam["url"] = protoArgs.Uri.AbsoluteUri; } Portable.Helpers.StateHelper.SessionState["LaunchData"] = navigationParam; SimpleIoc.Default.GetInstance<GalaSoft.MvvmLight.Views.INavigationService>().NavigateTo(ViewModelLocator.SplashPageKey); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { CoreApp.Initialize(Services.LocationServices.LocationService.Current, Services.DataServices.ProtoDataService.Current); await Task.Delay(500); NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; }
// *** Methods *** public Task<bool> Activate(IActivatedEventArgs activatedEventArgs) { if (activatedEventArgs == null) throw new ArgumentNullException(nameof(activatedEventArgs)); return ActivateInternal(activatedEventArgs); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { // long-running startup tasks go here NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; }
public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { if (args.Kind == ActivationKind.VoiceCommand) { var result = (args as VoiceCommandActivatedEventArgs).Result; var properties = result.SemanticInterpretation.Properties .ToDictionary(x => x.Key, x => x.Value); var command = result.RulePath.First(); if (command.Equals("FreeTextCommand")) { // get spoken text var text = properties.First(x => x.Key.Equals("textPhrase")).Value[0]; // remember to handle response appropriately var mode = properties.First(x => x.Key.Equals("commandMode")).Value; if (mode.Equals("voice")) { /* okay to speak */ } else { /* not okay to speak */ } // update value ViewModels.MainPageViewModel.Instance.Value = text; } else { /* unexpected command */ } } else { NavigationService.Navigate(typeof(Views.MainPage)); } return Task.CompletedTask; }
protected override async void OnActivated(IActivatedEventArgs e) { await InternalActivatedAsync(e); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; }
public override async Task OnInitializeAsync(IActivatedEventArgs args) { await Task.CompletedTask; }
protected override Task OnActivateApplicationAsync(IActivatedEventArgs args) { return(Task.CompletedTask); }
protected override async void OnActivated(IActivatedEventArgs args) { await ActivationService.ActivateAsync(args); }
private void ApplicationView_Activated(CoreApplicationView sender, IActivatedEventArgs args) { CoreWindow.GetForCurrentThread().Activate(); }
private async Task InternalActivatedAsync(IActivatedEventArgs e) { await this.OnActivatedAsync(e); Window.Current.Activate(); }
private async void CurrentOnContractActivated(object sender, IActivatedEventArgs activatedEventArgs) { FileOpenOrFolderPickerOpenend = false; var filePickerContinuationArgs = activatedEventArgs as FileOpenPickerContinuationEventArgs; if (filePickerContinuationArgs != null) { this.FilePickerContinuationArgs = filePickerContinuationArgs; return; } var folderPickerContinuationArgs = activatedEventArgs as FolderPickerContinuationEventArgs; if (folderPickerContinuationArgs != null) { CloudDrive.PickerOrDialogIsOpen = false; // If folder selected if (folderPickerContinuationArgs.Folder != null) { try { if (!StorageApplicationPermissions.FutureAccessList.CheckAccess(folderPickerContinuationArgs.Folder)) { StorageApplicationPermissions.FutureAccessList.Add(folderPickerContinuationArgs.Folder); } } catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error selecting external folder", e); string title = e is UnauthorizedAccessException ? AppMessages.FolderUnauthorizedAccess_Title : AppMessages.SelectFolderFailed_Title; string message = e is UnauthorizedAccessException? String.Format(AppMessages.FolderUnauthorizedAccess, folderPickerContinuationArgs.Folder.Name) : AppMessages.SelectFolderFailed; new CustomMessageDialog(title, message, App.AppInformation).ShowDialog(); return; } if (folderPickerContinuationArgs.ContinuationData["Operation"].ToString() == "SelectDefaultDownloadFolder") { SettingsService.SaveSetting(SettingsResources.DefaultDownloadLocation, folderPickerContinuationArgs.Folder.Path); this.FolderPickerContinuationArgs = null; } if (folderPickerContinuationArgs.ContinuationData["Operation"].ToString() == "SelectDownloadFolder") { this.FolderPickerContinuationArgs = folderPickerContinuationArgs; } if (folderPickerContinuationArgs.ContinuationData["Operation"].ToString() == "SelectLogFileSaveLocation") { // If user has selected an external location to save the log file move it to the selected location await FileService.MoveFile(AppService.GetFileLogPath(), folderPickerContinuationArgs.Folder.Path); this.FolderPickerContinuationArgs = null; } } else // If no folder selected { if (folderPickerContinuationArgs.ContinuationData["Operation"].ToString() == "SelectLogFileSaveLocation") { // If user said 'yes' to save the log file but canceled the selection of an external location, delete it anyway. FileService.DeleteFile(AppService.GetFileLogPath()); if (App.SavedForOfflineViewModel != null) { App.SavedForOfflineViewModel.SavedForOffline.Refresh(); } } } } }
private async Task InitializeAsync(IActivatedEventArgs e, bool preLaunchActivated = false) { try { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { //this.DebugSettings.EnableFrameRateCounter = true; //this.DebugSettings.EnableRedrawRegions = true; //this.DebugSettings.IsOverdrawHeatMapEnabled = true; //this.DebugSettings.IsBindingTracingEnabled = true; //this.DebugSettings.IsTextPerformanceVisualizationEnabled = true; } if (e.PreviousExecutionState != ApplicationExecutionState.Running) { this.DebugSettings.BindingFailed += DebugSettings_BindingFailed; } #endif if (e.PreviousExecutionState != ApplicationExecutionState.Running) { // No need to run any of this logic if the app is already running // Ensure unobserved task exceptions (unawaited async methods returning Task or Task<T>) are handled TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Determine if the app is a new instance or being restored after app suspension if (e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser || e.PreviousExecutionState == ApplicationExecutionState.NotRunning) { await Platform.Current.AppInitializingAsync(InitializationModes.New); } else { await Platform.Current.AppInitializingAsync(InitializationModes.Restore); } } //Turn off Title Safe Area overscan adjustment if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationViewBoundsMode") && Platform.DeviceFamily == DeviceFamily.Xbox) { var AppView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView(); AppView.SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow); } ////Turn of scaling, if app is not designed at 540p (Xbox One default scaling is 200% for XAML, 150% for Web Programming model apps) //if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent( // "Windows.UI.ViewManagement.ApplicationViewScaling")) //{ // Windows.UI.ViewManagement.ApplicationViewScaling.TrySetDisableLayoutScaling(true); //} 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 ApplicationFrame(); // Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "RootFrame"); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { try { // Restore the saved session state only when appropriate await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue } } } if (preLaunchActivated == false) { // Manage activation and process arguments Platform.Current.Navigation.HandleActivation(e, rootFrame); // Ensure the current window is active Window.Current.Activate(); ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(320, 200)); } } catch (Exception ex) { Platform.Current.Logger.LogErrorFatal(ex, "Error during App InitializeAsync(e)"); throw ex; } }
public virtual Task OnActivatedAsync(IActivatedEventArgs e) { return(Task.FromResult <object>(null)); }
private async Task HandleProtocolActivation(IActivatedEventArgs args) { var protocolArgs = (ProtocolActivatedEventArgs)args; var uri = protocolArgs.Uri; if (string.IsNullOrEmpty(uri.Query)) { return; } WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query); switch (uri.Host) { case "goto": if (decoder[0]?.Name == "page") { if (decoder[0]?.Value == VLCPage.SettingsPageUI.ToString()) { Locator.NavigationService.Go(VLCPage.SettingsPageUI); } } break; case "openstream": // do stuff if (decoder[0]?.Name == "from") { switch (decoder[0]?.Value) { case "clipboard": await Task.Delay(1000); var dataPackage = Clipboard.GetContent(); Uri url = null; if (dataPackage.Contains(StandardDataFormats.ApplicationLink)) { url = await dataPackage.GetApplicationLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.WebLink)) { url = await dataPackage.GetWebLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.Text)) { url = new Uri(await dataPackage.GetTextAsync()); } if (url != null) { await Locator.MediaPlaybackViewModel.PlayStream(url.AbsoluteUri); } break; case "useraction": Locator.MainVM.GoToStreamPanel.Execute(null); break; case "url": if (decoder[1]?.Name == "url") { StorageFile subsFd = null; try { var subsFrom = decoder.Where((item, index) => item.Name == "subs_from").FirstOrDefault(); var subsValue = decoder.Where((item, index) => item.Name == "subs").FirstOrDefault(); if (!(subsFrom == default(IWwwFormUrlDecoderEntry) && subsValue == default(IWwwFormUrlDecoderEntry))) { switch (subsFrom.Value) { case "path": //this StorageFile is like a File Descriptor from Unix subsFd = await StorageFile.GetFileFromPathAsync(subsValue.Value); if (subsFd == null) { ToastHelper.Basic("Failed to Load Subtitles: Couln´t find the file."); } else if (!StorageApplicationPermissions.FutureAccessList.CheckAccess(subsFd)) { StorageApplicationPermissions.FutureAccessList.Add(subsFd); } break; case "url": using (var httpClient = new System.Net.Http.HttpClient()) { var subsContent = await httpClient.GetStringAsync(subsValue.Value); subsFd = await ApplicationData.Current.LocalFolder.CreateFileAsync(subsContent.GetHashCode().ToString(), CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(subsFd, subsContent); } break; case "picker": var openPicker = new FileOpenPicker(); openPicker.FileTypeFilter.Add(".srt"); openPicker.FileTypeFilter.Add(".txt"); openPicker.SuggestedStartLocation = PickerLocationId.Downloads; subsFd = await openPicker.PickSingleFileAsync(); break; } } } //StorageFile.GetFileFromPath or CreateFileAsync failed catch (UnauthorizedAccessException) { ToastHelper.Basic("Failed to Load Subtitles: Access Denied to the file."); } //HttpClient usually fails with an AggregateException instead of WebException or HttpRequest...Exception catch (AggregateException) { ToastHelper.Basic("Failed to Load Subtitles: Problems downloading the subtitles"); } //HttpClient fails with a WebException when there´s no connectivity catch (System.Net.WebException) { ToastHelper.Basic("Failed to Load Subtitles: No Connectivity"); } catch (Exception ex) { ToastHelper.Basic("Failed to Load Subtitles: " + ex.GetType().ToString()); } await Locator.MediaPlaybackViewModel.PlayStream(decoder[1].Value); if (subsFd != null) { ToastHelper.Basic("Subtitles Loaded Successfully"); Locator.MediaPlaybackViewModel.OpenSubtitleCommand.Execute(subsFd); } } break; } } break; } }
protected override void OnActivated(IActivatedEventArgs e) { base.OnActivated(e); if (e.Kind != Windows.ApplicationModel.Activation.ActivationKind.VoiceCommand) { return; } var commandArgs = e as Windows.ApplicationModel.Activation.VoiceCommandActivatedEventArgs; var speechRecognitionResult = commandArgs.Result; var command = speechRecognitionResult.Text; // Get the name of the voice command and the text spoken. string voiceCommandName = speechRecognitionResult.RulePath[0]; switch (voiceCommandName) { case "officelighton": MainPage.officelighton(); break; case "officelightoff": MainPage.officelightoff(); break; case "mainlighton": MainPage.mainlighton(); break; case "mainlightoff": MainPage.mainlightoff(); break; case "readinglighton": MainPage.readinglighton(); break; case "readinglightoff": MainPage.readinglightoff(); break; case "officedeviceson": MainPage.officedeviceson(); break; case "officedevicesoff": MainPage.officedevicesoff(); break; case "opendoor": MainPage.opendoor(); break; case "closedoor": MainPage.closedoor(); break; case "ledstripon": MainPage.ledstripon(); break; case "ledstriponblue": MainPage.ledstriponblue(); break; case "ledstriponred": MainPage.ledstriponred(); break; case "ledstripongreen": MainPage.ledstripongreen(); break; case "ledstriponyellow": MainPage.ledstriponyellow(); break; case "ledstriponcyan": MainPage.ledstriponcyan(); break; case "ledstriponorange": MainPage.ledstriponorange(); break; case "ledstriponpink": MainPage.ledstriponpink(); break; case "ledstriponpurple": MainPage.ledstripongreen(); break; case "ledstripoff": MainPage.ledstripoff(); break; case "allon": MainPage.allon(); break; case "alloff": MainPage.alloff(); break; case "ledstriponfade": MainPage.fadeon(); break; default: break; } 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(); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { //use the "command" which was spoken by the user. // i am just checking weather the Activation is by Voice command or not and navigating. if (e.Kind != Windows.ApplicationModel.Activation.ActivationKind.VoiceCommand) { rootFrame.Navigate(typeof(MainPage), e.Kind); } else { rootFrame.Navigate(typeof(MainPage), e.Kind); } // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter } // Ensure the current window is active Window.Current.Activate(); }
private async void UseActivatedArgs(IActivatedEventArgs args, INavigationService service) { if (service == null) { service = WindowContext.GetForCurrentView().NavigationServices.FirstOrDefault(); } if (service == null || args == null) { return; } if (args is ShareTargetActivatedEventArgs share) { var package = new DataPackage(); try { var operation = share.ShareOperation.Data; if (operation.AvailableFormats.Contains(StandardDataFormats.ApplicationLink)) { package.SetApplicationLink(await operation.GetApplicationLinkAsync()); } if (operation.AvailableFormats.Contains(StandardDataFormats.Bitmap)) { package.SetBitmap(await operation.GetBitmapAsync()); } //if (operation.Contains(StandardDataFormats.Html)) //{ // package.SetHtmlFormat(await operation.GetHtmlFormatAsync()); //} //if (operation.Contains(StandardDataFormats.Rtf)) //{ // package.SetRtf(await operation.GetRtfAsync()); //} if (operation.AvailableFormats.Contains(StandardDataFormats.StorageItems)) { package.SetStorageItems(await operation.GetStorageItemsAsync()); } if (operation.AvailableFormats.Contains(StandardDataFormats.Text)) { package.SetText(await operation.GetTextAsync()); } //if (operation.Contains(StandardDataFormats.Uri)) //{ // package.SetUri(await operation.GetUriAsync()); //} if (operation.AvailableFormats.Contains(StandardDataFormats.WebLink)) { package.SetWebLink(await operation.GetWebLinkAsync()); } } catch { } var query = "tg://"; var contactId = await ContactsService.GetContactIdAsync(share.ShareOperation.Contacts.FirstOrDefault()); if (contactId is int userId) { var response = await _lifetime.ActiveItem.ProtoService.SendAsync(new CreatePrivateChat(userId, false)); if (response is Chat chat) { query = $"ms-contact-profile://meh?ContactRemoteIds=u" + userId; App.DataPackages[chat.Id] = package.GetView(); } else { App.DataPackages[0] = package.GetView(); } } else { App.DataPackages[0] = package.GetView(); } App.ShareOperation = share.ShareOperation; App.ShareWindow = _window; var options = new Windows.System.LauncherOptions(); options.TargetApplicationPackageFamilyName = Package.Current.Id.FamilyName; try { await Windows.System.Launcher.LaunchUriAsync(new Uri(query), options); } catch { // It's too early? } } else if (args is VoiceCommandActivatedEventArgs voice) { SpeechRecognitionResult speechResult = voice.Result; string command = speechResult.RulePath[0]; if (command == "ShowAllDialogs") { service.NavigateToMain(null); } if (command == "ShowSpecificDialog") { //#TODO: Fix that this'll open a specific dialog service.NavigateToMain(null); } else { service.NavigateToMain(null); } } else if (args is ContactPanelActivatedEventArgs contact) { SetContactPanel(contact.ContactPanel); if (Application.Current.Resources.TryGet("PageHeaderBackgroundBrush", out SolidColorBrush backgroundBrush)) { contact.ContactPanel.HeaderColor = backgroundBrush.Color; } var contactId = await ContactsService.GetContactIdAsync(contact.Contact.Id); if (contactId is int userId) { var response = await _lifetime.ActiveItem.ProtoService.SendAsync(new CreatePrivateChat(userId, false)); if (response is Chat chat) { service.NavigateToChat(chat); } else { ContactPanelFallback(service); } } else { ContactPanelFallback(service); } } else if (args is ProtocolActivatedEventArgs protocol) { if (service?.Frame?.Content is MainPage page) { page.Activate(protocol.Uri.ToString()); } else { service.NavigateToMain(protocol.Uri.ToString()); } if (App.ShareOperation != null) { try { App.ShareOperation.ReportCompleted(); App.ShareOperation = null; } catch { } } if (App.ShareWindow != null) { try { await App.ShareWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { App.ShareWindow.Close(); App.ShareWindow = null; }); } catch { } } } else if (args is FileActivatedEventArgs file) { if (service?.Frame?.Content is MainPage page) { //page.Activate(launch); } else { service.NavigateToMain(string.Empty); } await new ThemePreviewPopup(file.Files[0].Path).ShowQueuedAsync(); } else { var activate = args as ToastNotificationActivatedEventArgs; var launched = args as LaunchActivatedEventArgs; var launch = activate?.Argument ?? launched?.Arguments; if (service?.Frame?.Content is MainPage page) { page.Activate(launch); } else { service.NavigateToMain(launch); } } }
protected override void OnActivated(IActivatedEventArgs e) { // Get the root frame var rootFrame = Window.Current.Content as Frame; // TODO: Initialize root frame just like in OnLaunched // Handle toast activation if (e is ToastNotificationActivatedEventArgs) { if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; //await CopyDatabase(); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } try { 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 navigatio n // parameter rootFrame.Navigate(typeof(Sospage)); } else { rootFrame.Navigate(typeof(Sospage)); } } catch (Exception exc) { Debug.WriteLine(exc); } if (rootFrame.BackStack.Count == 0) { rootFrame.BackStack.Add(new PageStackEntry(typeof(HomePage), null, null)); } } else if (e.Kind == ActivationKind.VoiceCommand) { if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; //await CopyDatabase(); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // 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(Sospage)); } else { rootFrame.Navigate(typeof(Sospage)); } if (rootFrame.BackStack.Count == 0) { rootFrame.BackStack.Add(new PageStackEntry(typeof(HomePage), null, null)); } } // TODO: Handle other types of activation // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// By default, Template 10 will setup the root element to be a Template 10 /// Modal Dialog control. If you desire something different, you can set it here. /// </summary> public abstract UIElement CreateRootElement(IActivatedEventArgs e);
protected override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); }
/// <summary> /// This handles all the preliminary stuff unique to Launched before calling OnStartAsync(). /// This is private because it is a specialized prelude to OnStartAsync(). /// OnStartAsync will not be called if state restore is determined /// </summary> private async Task InternalLaunchAsync(ILaunchActivatedEventArgs e) { DebugWrite($"Previous:{e.PreviousExecutionState.ToString()}"); OriginalActivatedArgs = e; if (e.PreviousExecutionState != ApplicationExecutionState.Running || Window.Current.Content == null) { try { await InitializeFrameAsync(e); } catch (Exception) { // nothing } } // okay, now handle launch bool restored = false; switch (e.PreviousExecutionState) { case ApplicationExecutionState.Suspended: case ApplicationExecutionState.Terminated: { OnResuming(this, null, AppExecutionState.Terminated); /* * Restore state if you need to/can do. * Remember that only the primary tile or when user has * switched to the app (for instance via the task switcher) * should restore. (this includes toast with no data payload) * The rest are already providing a nav path. * * In the event that the cache has expired, attempting to restore * from state will fail because of missing values. * This is okay & by design. */ restored = await CallAutoRestoreAsync(e, restored); break; } case ApplicationExecutionState.ClosedByUser: case ApplicationExecutionState.NotRunning: default: break; } // handle pre-launch if ((e as LaunchActivatedEventArgs)?.PrelaunchActivated ?? false) { var runOnStartAsync = false; _HasOnPrelaunchAsync = true; await OnPrelaunchAsync(e, out runOnStartAsync); if (!runOnStartAsync) { return; } } if (!restored) { var kind = e.PreviousExecutionState == ApplicationExecutionState.Running ? StartKind.Activate : StartKind.Launch; await CallOnStartAsync(true, kind); } CallActivateWindow(WindowLogic.ActivateWindowSources.Launching); }
public override abstract Task OnStartAsync(StartKind startKind, IActivatedEventArgs args);
protected override async void OnActivated(IActivatedEventArgs args) { Debug.WriteLine("OnActivated"); await ActivationService.ActivateAsync(args); }
/// <summary> /// OnInitializeAsync is where your app will do must-have up-front operations /// OnInitializeAsync will be called even if the application is restoring from state. /// An app restores from state when the app was suspended and then terminated (PreviousExecutionState terminated). /// </summary> public virtual Task OnInitializeAsync(IActivatedEventArgs args) { DebugWrite($"Virtual {nameof(IActivatedEventArgs)}:{args.Kind}"); return(Task.CompletedTask); }
/// <summary> /// Raises the applications Launch event. /// </summary> /// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param> public void OnLaunched(IActivatedEventArgs args) { _activated.OnNext(args); }
// it is the intent of Template 10 to no longer require Launched/Activated overrides, only OnStartAsync() protected override sealed void OnActivated(IActivatedEventArgs e) { DebugWrite(); CallInternalActivatedAsync(e); }
protected virtual Frame CreateRootFrame(IActivatedEventArgs e) { DebugWrite($"{nameof(IActivatedEventArgs)}:{e}"); return(new Frame()); }
// runs only when not restored from state public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { await Task.Delay(50); NavigationService.Navigate(typeof(Views.SearchPage)); }
private void OnAppLaunch(IActivatedEventArgs args, string argument) { // Uncomment the following lines to display frame-rate and per-frame CPU usage info. //#if _DEBUG // if (IsDebuggerPresent()) // { // DebugSettings->EnableFrameRateCounter = true; // } //#endif args.SplashScreen.Dismissed += DismissedEventHandler; var rootFrame = (Window.Current.Content as Frame); WeakReference weak = new WeakReference(this); float minWindowWidth = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowWidth]); float minWindowHeight = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowHeight]); Size minWindowSize = SizeHelper.FromDimensions(minWindowWidth, minWindowHeight); ApplicationView appView = ApplicationView.GetForCurrentView(); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; // For very first launch, set the size of the calc as size of the default standard mode if (!localSettings.Values.ContainsKey("VeryFirstLaunch")) { localSettings.Values["VeryFirstLaunch"] = false; appView.SetPreferredMinSize(minWindowSize); appView.TryResizeView(minWindowSize); } else { ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto; } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // PC Family { // Disable the system view activation policy during the first launch of the app // only for PC family devices and not for phone family devices try { ApplicationViewSwitcher.DisableSystemViewActivationPolicy(); } catch (Exception) { // Log that DisableSystemViewActionPolicy didn't work } } // Create a Frame to act as the navigation context rootFrame = App.CreateFrame(); // 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), argument)) { // We couldn't navigate to the main page, kill the app so we have a good // stack to debug throw new SystemException(); } SetMinWindowSizeAndThemeAndActivate(rootFrame, minWindowSize); m_mainViewId = ApplicationView.GetForCurrentView().Id; AddWindowToMap(WindowFrameService.CreateNewWindowFrameService(rootFrame, false, weak)); } else { // For first launch, LaunchStart is logged in constructor, this is for subsequent launches. // !Phone check is required because even in continuum mode user interaction mode is Mouse not Touch if ((UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse) && (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))) { // If the pre-launch hasn't happened then allow for the new window/view creation if (!m_preLaunched) { var newCoreAppView = CoreApplication.CreateNewView(); _ = newCoreAppView.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async() => { var that = weak.Target as App; if (that != null) { var newRootFrame = App.CreateFrame(); SetMinWindowSizeAndThemeAndActivate(newRootFrame, minWindowSize); if (!newRootFrame.Navigate(typeof(MainPage), argument)) { // We couldn't navigate to the main page, kill the app so we have a good // stack to debug throw new SystemException(); } var frameService = WindowFrameService.CreateNewWindowFrameService(newRootFrame, true, weak); that.AddWindowToMap(frameService); var dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; // CSHARP_MIGRATION_ANNOTATION: // class SafeFrameWindowCreation is being interpreted into a IDisposable class // in order to enhance its RAII capability that was written in C++/CX using (var safeFrameServiceCreation = new SafeFrameWindowCreation(frameService, that)) { int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()); ActivationViewSwitcher activationViewSwitcher = null; var activateEventArgs = (args as IViewSwitcherProvider); if (activateEventArgs != null) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } if (activationViewSwitcher != null) { _ = activationViewSwitcher.ShowAsStandaloneAsync(newWindowId, ViewSizePreference.Default); safeFrameServiceCreation.SetOperationSuccess(true); } else { var activatedEventArgs = (args as IApplicationViewActivatedEventArgs); if ((activatedEventArgs != null) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0)) { // CSHARP_MIGRATION_ANNOTATION: // here we don't use ContinueWith() to interpret origin code because we would like to // pursue the design of class SafeFrameWindowCreate whichi was using RAII to ensure // some states get handled properly when its instance is being destructed. // // To achieve that, SafeFrameWindowCreate has been reinterpreted using IDisposable // pattern, which forces we use below way to keep async works being controlled within // a same code block. var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync( frameService.GetViewId(), ViewSizePreference.Default, activatedEventArgs.CurrentlyShownApplicationViewId, ViewSizePreference.Default); // SafeFrameServiceCreation is used to automatically remove the frame // from the list of frames if something goes bad. safeFrameServiceCreation.SetOperationSuccess(viewShown); } } } } }); } else { ActivationViewSwitcher activationViewSwitcher = null; var activateEventArgs = (args as IViewSwitcherProvider); if (activateEventArgs != null) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } if (activationViewSwitcher != null) { _ = activationViewSwitcher.ShowAsStandaloneAsync( ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()), ViewSizePreference.Default); } else { TraceLogger.GetInstance().LogError(ViewMode.None, "App.OnAppLaunch", "Null_ActivationViewSwitcher"); } } // Set the preLaunched flag to false m_preLaunched = false; } else // for touch devices { 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(MainPage), argument)) { // We couldn't navigate to the main page, // kill the app so we have a good stack to debug throw new SystemException(); } } if (ApplicationView.GetForCurrentView().ViewMode != ApplicationViewMode.CompactOverlay) { if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) { // for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in // activationArgs ActivationViewSwitcher activationViewSwitcher = null; var activateEventArgs = (args as IViewSwitcherProvider); if (activateEventArgs != null) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } if (activationViewSwitcher != null) { var viewId = (args as IApplicationViewActivatedEventArgs).CurrentlyShownApplicationViewId; if (viewId != 0) { _ = activationViewSwitcher.ShowAsStandaloneAsync(viewId); } } } // Ensure the current window is active Window.Current.Activate(); } } } }
protected async override void OnActivated(IActivatedEventArgs args) { RegisterExceptionHandlingSynchronizationContext(); //bilibili://bangumi/season/21715 //bilibili://live/5619438 //bilibili://video/19239064 //bilibili://clip/1399466 //bilibili://pgc/review/11592?url_from_h5=1 点评 //bilibili://article/242568 //bilibili://music/detail/247991?name=2018%E5%B8%9D%E7%8E%96%E6%BC%94%E5%A5%8F%E8%AE%A1%E5%88%92%EF%BC%9A%E4%BA%A4%E5%93%8D%E7%BB%84%E6%9B%B2%E3%80%8C%E5%90%9B%E3%81%AE%E5%90%8D%E3%81%AF%E3%80%82%E3%80%8D&cover_url=http:%2F%2Fi0.hdslb.com%2Fbfs%2Fmusic%2F9892d28aa5858a571e4a832d314e2136211ad7f7.jpg&from=outer_h5 //bilibili://album/2403422 //bilibili://author/2622476 // bilibili://music/menu/detail/78723 if (args.Kind == ActivationKind.Protocol) { Frame rootFrame = Window.Current.Content as Frame; StartModel par = new StartModel() { StartType = StartTypes.HandelUri }; ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs; par.Par1 = eventArgs.Uri.AbsoluteUri; //string video = Regex.Match(eventArgs.Uri.AbsoluteUri, @"video/(\d+)").Groups[1].Value; //string video2 = Regex.Match(eventArgs.Uri.AbsoluteUri.Replace("/","").Replace("=",""), @"av(\d+)").Groups[1].Value; //string live = Regex.Match(eventArgs.Uri.AbsoluteUri, @"live/(\d+)").Groups[1].Value; //string minivideo = Regex.Match(eventArgs.Uri.AbsoluteUri, @"clip/(\d+)").Groups[1].Value; //string bangumi = Regex.Match(eventArgs.Uri.AbsoluteUri, @"season/(\d+)").Groups[1].Value; //string music = Regex.Match(eventArgs.Uri.AbsoluteUri, @"music/detail/(\d+)").Groups[1].Value; //string album = Regex.Match(eventArgs.Uri.AbsoluteUri, @"album/(\d+)").Groups[1].Value; //string article = Regex.Match(eventArgs.Uri.AbsoluteUri, @"article/(\d+)").Groups[1].Value; //string author = Regex.Match(eventArgs.Uri.AbsoluteUri, @"author/(\d+)").Groups[1].Value; if (rootFrame != null) { if (!await MessageCenter.HandelUrl(eventArgs.Uri.AbsoluteUri)) { ContentDialog contentDialog = new ContentDialog() { PrimaryButtonText = "确定", Title = "不支持跳转的地址" }; TextBlock textBlock = new TextBlock() { Text = eventArgs.Uri.AbsoluteUri, IsTextSelectionEnabled = true }; contentDialog.Content = textBlock; contentDialog.ShowAsync(); } } else { SYEngine.Core.Initialize(); // 创建要充当导航上下文的框架,并导航到第一页 rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; // 将框架放在当前窗口中 Window.Current.Content = rootFrame; rootFrame.Navigate(typeof(SplashPage), par); Window.Current.Activate(); } //if (live.Length != 0) //{ // par.StartType = StartTypes.Live; // par.Par1 = live; // if (rootFrame!=null) // { // MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), live); // return; // } //} //if (video.Length != 0) //{ // par.StartType = StartTypes.Video; // par.Par1 = video; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), video); // return; // } //} //if (video2.Length != 0) //{ // par.StartType = StartTypes.Video; // par.Par1 = video2; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), video2); // return; // } //} //if (minivideo.Length != 0) //{ // par.StartType = StartTypes.MiniVideo; // par.Par1 = minivideo; // if (rootFrame != null) // { // MessageCenter.ShowMiniVideo(minivideo); // return; // } //} //if (bangumi.Length != 0) //{ // par.StartType = StartTypes.Bangumi; // par.Par1 = bangumi; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), bangumi); // return; // } //} //if (album.Length != 0) //{ // par.StartType = StartTypes.Album; // par.Par1 = album; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(DynamicInfoPage), album); // return; // } //} //if (music.Length != 0) //{ // par.StartType = StartTypes.Music; // par.Par1 = music; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(MusicInfoPage), music); // return; // } //} //if (musicmenu.Length != 0) //{ // par.StartType = StartTypes.Music; // par.Par1 = music; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(MusicInfoPage), music); // return; // } //} //if (article.Length != 0) //{ // par.StartType = StartTypes.Article; // par.Par1 = "https://www.bilibili.com/read/app/" + article; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(ArticleContentPage), "https://www.bilibili.com/read/app/" + article); // return; // } //} //if (author.Length != 0) //{ // par.StartType = StartTypes.User; // par.Par1 = author; // if (rootFrame != null) // { // MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(UserInfoPage), author); // return; // } //} } }
public static void Init(IActivatedEventArgs launchActivatedEventArgs, IEnumerable <Assembly> rendererAssemblies = null)
// it is the intent of Template 10 to no longer require Launched/Activated overrides, only OnStartAsync() protected override sealed async void OnActivated(IActivatedEventArgs e) { DebugWrite(); await InternalActivatedAsync(e).ConfigureAwait(false); }
protected override async void OnActivated(IActivatedEventArgs args) { if (args is ProtocolActivatedEventArgs protocolActivated) { if (protocolActivated.Uri == new Uri("ftcmd://fluent.terminal?focus")) { await ShowOrCreateWindow(protocolActivated.ViewSwitcher); return; } MainViewModel mainViewModel = null; // IApplicationView to use for creating view models IApplicationView applicationView; if (_alreadyLaunched) { applicationView = (_mainViewModels.FirstOrDefault(o => o.ApplicationView.Id == _activeWindowId) ?? _mainViewModels.Last()).ApplicationView; } else { // App wasn't launched before double clicking a shortcut, so we have to create a window // in order to be able to communicate with user. mainViewModel = _container.Resolve <MainViewModel>(); await CreateMainView(typeof(MainPage), mainViewModel, true); applicationView = mainViewModel.ApplicationView; } bool isSsh; try { isSsh = SshConnectViewModel.CheckScheme(protocolActivated.Uri); } catch (Exception ex) { await new MessageDialog( $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}", "Invalid Link") .ShowAsync(); mainViewModel?.ApplicationView.TryClose(); return; } if (isSsh) { SshConnectViewModel vm; try { vm = SshConnectViewModel.ParseUri(protocolActivated.Uri, _settingsService, applicationView, _trayProcessCommunicationService, _container.Resolve <IFileSystemService>(), _container.Resolve <ApplicationDataContainers>().HistoryContainer); } catch (Exception ex) { await new MessageDialog( $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}", "Invalid Link") .ShowAsync(); mainViewModel?.ApplicationView.TryClose(); return; } if (_applicationSettings.AutoFallbackToWindowsUsernameInLinks && string.IsNullOrEmpty(vm.Username)) { vm.Username = await _trayProcessCommunicationService.GetUserName(); } var error = await vm.AcceptChangesAsync(true); SshProfile profile = (SshProfile)vm.Model; if (!string.IsNullOrEmpty(error)) { // Link is valid, but incomplete (i.e. username missing), so we need to show dialog. profile = await _dialogService.ShowSshConnectionInfoDialogAsync(profile); if (profile == null) { // User clicked "Cancel" in the dialog. mainViewModel?.ApplicationView.TryClose(); return; } } if (mainViewModel == null) { await CreateTerminal(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher); } else { await mainViewModel.AddTerminalAsync(profile); } return; } if (CommandProfileProviderViewModel.CheckScheme(protocolActivated.Uri)) { CommandProfileProviderViewModel vm; try { vm = CommandProfileProviderViewModel.ParseUri(protocolActivated.Uri, _settingsService, applicationView, _trayProcessCommunicationService, _container.Resolve <ApplicationDataContainers>().HistoryContainer); } catch (Exception ex) { await new MessageDialog( $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}", "Invalid Link") .ShowAsync(); mainViewModel?.ApplicationView.TryClose(); return; } var error = await vm.AcceptChangesAsync(true); var profile = vm.Model; if (!string.IsNullOrEmpty(error)) { // Link is valid, but incomplete, so we need to show dialog. profile = await _dialogService.ShowCustomCommandDialogAsync(profile); if (profile == null) { // User clicked "Cancel" in the dialog. mainViewModel?.ApplicationView.TryClose(); return; } } if (mainViewModel == null) { await CreateTerminal(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher); } else { await mainViewModel.AddTerminalAsync(profile); } return; } await new MessageDialog( $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {protocolActivated.Uri}", "Invalid Link") .ShowAsync(); mainViewModel?.ApplicationView.TryClose(); return; } if (args is CommandLineActivatedEventArgs commandLineActivated) { var arguments = commandLineActivated.Operation.Arguments; if (string.IsNullOrWhiteSpace(arguments)) { arguments = "new"; } _commandLineParser.ParseArguments(SplitArguments(arguments), typeof(NewVerb), typeof(RunVerb), typeof(SettingsVerb)).WithParsed(async verb => { if (verb is SettingsVerb settingsVerb) { if (!settingsVerb.Import && !settingsVerb.Export) { await ShowSettings().ConfigureAwait(true); } else if (settingsVerb.Export) { var exportFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("config.json", CreationCollisionOption.OpenIfExists); var settings = _settingsService.ExportSettings(); await FileIO.WriteTextAsync(exportFile, settings); await new MessageDialog($"{I18N.Translate("SettingsExported")} {exportFile.Path}").ShowAsync(); } else if (settingsVerb.Import) { var file = await ApplicationData.Current.LocalFolder.GetFileAsync("config.json"); var content = await FileIO.ReadTextAsync(file); _settingsService.ImportSettings(content); await new MessageDialog($"{I18N.Translate("SettingsImported")} {file.Path}").ShowAsync(); } } else if (verb is NewVerb newVerb) { var profile = default(ShellProfile); if (!string.IsNullOrWhiteSpace(newVerb.Profile)) { profile = _settingsService.GetShellProfiles().FirstOrDefault(x => x.Name.Equals(newVerb.Profile, StringComparison.CurrentCultureIgnoreCase)); } if (profile == null) { profile = _settingsService.GetDefaultShellProfile(); } if (!string.IsNullOrWhiteSpace(newVerb.Directory) && newVerb.Directory != ".") { profile.WorkingDirectory = newVerb.Directory; } else { profile.WorkingDirectory = commandLineActivated.Operation.CurrentDirectoryPath; } var location = newVerb.Target == Target.Default ? _applicationSettings.NewTerminalLocation : newVerb.Target == Target.Tab ? NewTerminalLocation.Tab : NewTerminalLocation.Window; await CreateTerminal(profile, location).ConfigureAwait(true); } else if (verb is RunVerb runVerb) { var profile = new ShellProfile { Id = Guid.Empty, Location = null, Arguments = runVerb.Command, WorkingDirectory = runVerb.Directory }; if (!string.IsNullOrWhiteSpace(runVerb.Theme)) { var theme = _settingsService.GetThemes().FirstOrDefault(x => x.Name.Equals(runVerb.Theme, StringComparison.CurrentCultureIgnoreCase)); if (theme != null) { profile.TerminalThemeId = theme.Id; } } if (string.IsNullOrWhiteSpace(profile.WorkingDirectory)) { profile.WorkingDirectory = commandLineActivated.Operation.CurrentDirectoryPath; } var location = runVerb.Target == Target.Default ? _applicationSettings.NewTerminalLocation : runVerb.Target == Target.Tab ? NewTerminalLocation.Tab : NewTerminalLocation.Window; await CreateTerminal(profile, location).ConfigureAwait(true); } }); } }
public override Task OnInitializeAsync(IActivatedEventArgs args) { return(base.OnInitializeAsync(args)); }