protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; if (taskInstance.TriggerDetails is AppServiceTriggerDetails) { AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; AppServiceDeferral = taskInstance.GetDeferral(); // Ottiene un deferral così che il servizio non termina taskInstance.Canceled += OnAppServicesCanceled; // Associa un gestore di cancellazione al task in background Connection = appService.AppServiceConnection; Connection.RequestReceived += OnAppServiceRequestReceived; Connection.ServiceClosed += AppServiceConnection_ServiceClosed; // Sezione critica lock (ThisLock) { Connection.AppServiceName = ConnectionIndex.ToString(); Connections.Add(ConnectionIndex, Connection); AppServiceDeferrals.Add(ConnectionIndex, AppServiceDeferral); ConnectionIndex++; } } }
public async void Run(IBackgroundTaskInstance taskInstance) { // Create the deferral by requesting it from the task instance serviceDeferral = taskInstance.GetDeferral(); AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails != null && triggerDetails.Name.Equals("VoiceCommandService")) { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Perform the appropriate command depending on the operation defined in VCD switch (voiceCommand.CommandName) { case "CheckTemperature": VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage(); userMessage.DisplayMessage = "The current temperature is 23 degrees"; userMessage.SpokenMessage = "The current temperature is 23 degrees"; VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null); await voiceServiceConnection.ReportSuccessAsync(response); break; default: break; } } // Once the asynchronous method(s) are done, close the deferral serviceDeferral.Complete(); }
public AppServiceConnectionReceiver(IBackgroundTaskInstance instance, AppServiceTriggerDetails appServiceTriggerDetails) : base(appServiceTriggerDetails.AppServiceConnection, true) { ConnectionAlive = true; ServiceDeferral = instance.GetDeferral(); instance.Canceled += OnAppServiceCancelled; }
/// <summary> /// Helper method for initalizing the voice service, bridge, and lights. Returns if successful. /// </summary> private async Task <bool> InitializeAsync(AppServiceTriggerDetails triggerDetails) { _voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); _voiceServiceConnection.VoiceCommandCompleted += (s, e) => _deferral.Complete(); _voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync(); _colors = HsbColor.CreateAll().ToDictionary(x => x.Name); var localStorage = ApplicationData.Current.LocalSettings.Values; _bridge = new Bridge( localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString()); try { _lights = await _bridge.GetLightsAsync(); } catch (Exception) { var response = CreateCortanaResponse("Sorry, I couldn't connect to your bridge."); await _voiceServiceConnection.ReportFailureAsync(response); return(false); } if (!_lights.Any()) { var response = CreateCortanaResponse("Sorry, I couldn't find any lights."); await _voiceServiceConnection.ReportFailureAsync(response); return(false); } return(true); }
private async void App_AppServiceConnected(object sender, AppServiceTriggerDetails e) { App.Connection.RequestReceived += AppServiceConnection_RequestReceived; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { // Connected }); }
/// <summary> /// Initializes the app service on the host process /// </summary> protected async override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; if (taskInstance.TriggerDetails is AppServiceTriggerDetails) { AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (appService.CallerPackageFamilyName == Windows.ApplicationModel.Package.Current.Id.FamilyName) // App service connection from desktopBridge App { this.desktopBridgeAppServiceDeferral = taskInstance.GetDeferral(); // Get a deferral so that the service isn't terminated. taskInstance.Canceled += OndesktopBridgeAppServicesCanceled; // Associate a cancellation handler with the background task. this.desktopBridgeConnection = appService.AppServiceConnection; this.desktopBridgeConnection.RequestReceived += OndesktopBridgeAppServiceRequestReceived; this.desktopBridgeConnection.ServiceClosed += desktopBridgeAppServiceConnection_ServiceClosed; lock (thisLock) { this.desktopBridgeConnection.AppServiceName = desktopBridgeConnectionIndex.ToString(); desktopBridgeConnections.Add(desktopBridgeConnectionIndex, this.desktopBridgeConnection); desktopBridgeAppServiceDeferrals.Add(desktopBridgeConnectionIndex, this.desktopBridgeAppServiceDeferral); desktopBridgeConnectionIndex++; } // wait before configuring RequestReceived this.edgeConnection.RequestReceived += OnAppServiceRequestReceived; } else // App service connection from Edge browser { this.appServiceDeferral = taskInstance.GetDeferral(); // Get a deferral so that the service isn't terminated. taskInstance.Canceled += OnAppServicesCanceled; // Associate a cancellation handler with the background task. this.connection = appService.AppServiceConnection; this.edgeConnection = this.connection; this.connection.ServiceClosed += AppServiceConnection_ServiceClosed; lock (thisLock) { this.connection.AppServiceName = connectionIndex.ToString(); connections.Add(connectionIndex, this.connection); appServiceDeferrals.Add(connectionIndex, this.appServiceDeferral); connectionIndex++; } try { // Make sure the PasswordInputProtection.exe is in your AppX folder, if not rebuild the solution await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } catch (Exception) { this.desktopBridgeAppLaunched = false; MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the PasswordInputProtection.exe is in your AppX folder"); await dialog.ShowAsync(); } } } }
/// <summary> /// When the desktop process is connected, get ready to send/receive requests /// </summary> private async void MainPage_AppServiceConnected(object sender, AppServiceTriggerDetails e) { App.Connection.RequestReceived += AppServiceConnection_RequestReceived; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // enable UI to access the connection btnRegKey.IsEnabled = true; }); }
public async void Run(IBackgroundTaskInstance taskInstance) { serviceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskInstance_Canceled; httpClient = new HttpClient(); AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails != null && triggerDetails.Name == "HuemongousVoiceCommandService") { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); voiceServiceConnection.VoiceCommandCompleted += VoiceServiceConnection_VoiceCommandCompleted; VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); if (voiceCommand.CommandName == "LightsOnOrOff") { string lightState = voiceCommand.Properties["lightState"][0]; await HandleLightsOnOrOff(lightState); } else if (voiceCommand.CommandName == "LightOnOrOff") { string lightState = voiceCommand.Properties["lightState"][0]; string lightOrRoom = voiceCommand.Properties["lightOrRoom"][0]; string lightPlurality = voiceCommand.Properties["lightPlurality"][0]; await HandleLightOnOrOff(lightState, lightOrRoom, lightPlurality); } else if (voiceCommand.CommandName == "SpecifyLightOnOrOff") { string lightState = voiceCommand.Properties["lightState"][0]; } else if (voiceCommand.CommandName == "SetLightScene") { string scene = voiceCommand.Properties["scene"][0]; } else if (voiceCommand.CommandName == "SetLightsColor") { string color = voiceCommand.Properties["color"][0]; await HandleSetLightsColor(color); } else if (voiceCommand.CommandName == "SetLightColor") { string lightOrRoom = voiceCommand.Properties["lightOrRoom"][0]; string lightPlurality = voiceCommand.Properties["lightPlurality"][0]; string color = voiceCommand.Properties["color"][0]; } else if (voiceCommand.CommandName == "SpecifyLightColor") { string color = voiceCommand.Properties["color"][0]; } else { Debug.WriteLine("unknown command"); } } }
internal void HandleBackgroundActivation(AppServiceTriggerDetails appServiceTriggerDetails) { if (appServiceTriggerDetails != null) { appServiceTriggerDetails.AppServiceConnection.RequestReceived += AppServiceConnection_RequestReceived; appServiceTriggerDetails.AppServiceConnection.ServiceClosed += AppServiceConnection_ServiceClosed; } }
/// <summary> /// Initializes the app service on the host process /// </summary> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { appServiceDeferral = args.TaskInstance.GetDeferral(); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; Connection = details.AppServiceConnection; } }
//App Service // see https://blogs.msdn.microsoft.com/appconsult/2016/12/19/desktop-bridge-the-migrate-phase-invoking-a-win32-process-from-a-uwp-app/ public static void OnAppServiceActivated(BackgroundActivatedEventArgs args) { IBackgroundTaskInstance taskInstance = args.TaskInstance; AppServiceTriggerDetails details = (AppServiceTriggerDetails)args.TaskInstance.TriggerDetails; appServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnAppServiceCanceled; appServiceConnection = details.AppServiceConnection; AppServiceConnected?.Invoke(null, null); }
public void OnBackgroundActivated(BackgroundActivatedEventArgs args) { IBackgroundTaskInstance taskInstance = args.TaskInstance; AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; _simulatorAppServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnAppServicesCanceled; _simulatorAppServiceConnection = appService.AppServiceConnection; _simulatorAppServiceConnection.RequestReceived += OnAppServiceRequestReceived; _simulatorAppServiceConnection.ServiceClosed += AppServiceConnection_ServiceClosed; }
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { appServiceDeferral = args.TaskInstance.GetDeferral(); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; var desktopBridgeService = Container.Resolve <IDesktopBridgeService>(); desktopBridgeService.Connection = details.AppServiceConnection; } }
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (appService?.Name == "com.roamit.notificationservice") { notificationAppServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled -= OnNotificationAppServicesCanceled; taskInstance.Canceled += OnNotificationAppServicesCanceled; notificationAppServiceConnection = appService.AppServiceConnection; notificationAppServiceConnection.RequestReceived -= OnNotificationAppServiceRequestReceived; notificationAppServiceConnection.RequestReceived += OnNotificationAppServiceRequestReceived; notificationAppServiceConnection.ServiceClosed -= NotificationAppServiceConnection_ServiceClosed; notificationAppServiceConnection.ServiceClosed += NotificationAppServiceConnection_ServiceClosed; } else if (appService?.Name == "com.roamit.messagecarrierservice") { messageCarrierAppServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled -= OnMessageCarrierAppServicesCanceled; taskInstance.Canceled += OnMessageCarrierAppServicesCanceled; messageCarrierAppServiceConnection = appService.AppServiceConnection; messageCarrierAppServiceConnection.RequestReceived -= OnMessageCarrierAppServiceRequestReceived; messageCarrierAppServiceConnection.RequestReceived += OnMessageCarrierAppServiceRequestReceived; messageCarrierAppServiceConnection.ServiceClosed -= MessageCarrierAppServiceConnection_ServiceClosed; messageCarrierAppServiceConnection.ServiceClosed += MessageCarrierAppServiceConnection_ServiceClosed; } else if (appService?.Name == "com.roamit.pcservice") { pcAppServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled -= OnPCAppServicesCanceled; taskInstance.Canceled += OnPCAppServicesCanceled; pcAppServiceConnection = appService.AppServiceConnection; pcAppServiceConnection.RequestReceived -= OnPCAppServiceRequestReceived; pcAppServiceConnection.RequestReceived += OnPCAppServiceRequestReceived; pcAppServiceConnection.ServiceClosed -= PCAppServiceConnection_ServiceClosed; pcAppServiceConnection.ServiceClosed += PCAppServiceConnection_ServiceClosed; } else if (appService?.Name == "com.roamit.serviceinapp") { InitCommunicationService(); communicationServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled -= OnCommunicationServicesCanceled; taskInstance.Canceled += OnCommunicationServicesCanceled; communicationServiceConnection = appService.AppServiceConnection; communicationServiceConnection.RequestReceived -= OnCommunicationServiceRequestReceived; communicationServiceConnection.RequestReceived += OnCommunicationServiceRequestReceived; communicationServiceConnection.ServiceClosed -= CommunicationServiceConnection_ServiceClosed; communicationServiceConnection.ServiceClosed += CommunicationServiceConnection_ServiceClosed; } }
/// <summary> /// Adapted https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos/blob/master/SecureInput/NativeMessagingHostInProcess/App.xaml.cs /// </summary> /// <param name="args"></param> protected async override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; if (taskInstance.TriggerDetails is AppServiceTriggerDetails) { AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; this.connection = new EdgeConnection(taskInstance.GetDeferral(), appService); } }
/// <summary> /// Initializes the app service on the host process /// </summary> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { BackgroundTaskDeferral appServiceDeferral = args.TaskInstance.GetDeferral(); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; Connection = details.AppServiceConnection; Messenger.Default.Send <ConnectionReadyMessage>(new ConnectionReadyMessage()); } }
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; _appServiceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnAppServicesCanceled; _appServiceConnection = appService.AppServiceConnection; _appServiceConnection.RequestReceived += OnAppServiceRequestReceived; _appServiceConnection.ServiceClosed += AppServiceConnection_ServiceClosed; }
/// <summary> /// Initializes the app service on the host process /// </summary> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { appServiceDeferral = args.TaskInstance.GetDeferral(); args.TaskInstance.Canceled += OnTaskCanceled; // Associate a cancellation handler with the background task. AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; Connection = details.AppServiceConnection; } }
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { //this method is invoked when the Win32 process requests to open the communication channel with the App Service base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { appServiceDeferral = args.TaskInstance.GetDeferral(); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; Connection = details.AppServiceConnection; //we subscribe to the RequestReceived event, which is triggered when the Win32 app sends some data through the channel Connection.RequestReceived += Connection_RequestReceived; } }
/* Unused, because this project does not yet need localised resources * /// <summary> * /// ResourceMap containing localized strings for display in Cortana. * /// </summary> * ResourceMap cortanaResourceMap; * * /// <summary> * /// The context for localized strings. * /// </summary> * ResourceContext cortanaContext; */ public async void Run(IBackgroundTaskInstance taskInstance) { //Use to let Cortana know what's up serviceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled; AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails != null && triggerDetails.Name == "AdventureWorksVoiceCommandService") { try { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails( triggerDetails); voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted; VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Perform the appropriate command (defined in Manto:MantoCortanaCommands.xml) switch (voiceCommand.CommandName) { case "whenIsTripToDestination": var destination = voiceCommand.Properties["destination"][0]; await SendCompletionMessageForDestination(destination); break; case "cancelTripToDestination": var cancelDestination = voiceCommand.Properties["destination"][0]; await SendCompletionMessageForCancellation(cancelDestination); break; default: // As with app activation VCDs, we need to handle the possibility that // an app update may remove a voice command that is still registered. // This can happen if the user hasn't run an app since an update. LaunchAppInForeground(); break; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString()); } } }
public void Run(IBackgroundTaskInstance taskInstance) { AppServiceTriggerDetails triggerDetail = taskInstance.TriggerDetails as AppServiceTriggerDetails; _deferral = taskInstance.GetDeferral(); // Register for Task Cancel callback taskInstance.Canceled += TaskInstance_Canceled; AppServiceConnection connection = triggerDetail.AppServiceConnection; _connection = connection; connection.RequestReceived += Connection_RequestReceived; }
public void AddConnection(IBackgroundTaskInstance taskInstance, AppServiceTriggerDetails triggerDetails) { var deferral = taskInstance.GetDeferral(); var connection = triggerDetails.AppServiceConnection; taskInstance.Canceled += Connection_Disconnected; connection.RequestReceived += Connection_RequestReceived; connection.ServiceClosed += Connection_ServiceClosed; var connectionInfo = new ConnectionInfo(deferral, taskInstance); _connections.Add(connection, connectionInfo); Debug.WriteLine("New connection " + taskInstance.InstanceId); }
private void CustomSnowFallFromAppServiceAsync( IBackgroundTaskInstance instance, AppServiceTriggerDetails details) { var def = instance.GetDeferral(); instance.Canceled += (_, __) => { def.Complete(); }; details.AppServiceConnection.RequestReceived += (_, message) => { var messageDef = message.GetDeferral(); try { try { // lecture du message var targetUri = message.Request.Message.FirstOrDefault(kVp => kVp.Key == "targetUri").Value?.ToString(); if (!string.IsNullOrEmpty(targetUri)) { // Uri locale = pas de téléchargement if (targetUri.StartsWith("ms-appx")) { DispatcherHelper.CheckBeginInvokeOnUIAsync(() => SnowFallAsync(true, new BitmapImage(new Uri(targetUri)))); return; } DispatcherHelper.CheckBeginInvokeOnUIAsync( async() => { // téléchargement local de l'image var image = await Microsoft.Toolkit.Uwp.UI.ImageCache.GetFromCacheAsync(new Uri(targetUri)); SnowFallAsync(true, image); }); } } finally { // fermeture du message messageDef.Complete(); } } finally { // On ne fera pas d'autres communications def.Complete(); } }; }
public void Run(IBackgroundTaskInstance taskInstance) { taskDeferral = taskInstance.GetDeferral(); //taskInstance.Canceled += OnTaskCanceled; AppServiceTriggerDetails details = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (details != null) { string serviceName = details.Name; if (serviceName == "SunCashierSecondService") { AppServiceConnection conn = details.AppServiceConnection; conn.RequestReceived += Conn_RequestReceived; } } }
/// <summary> /// Invoked when our application is activated in the background. /// </summary> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); // if we've been triggered by the app service if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { BackgroundTaskDeferral appServiceDeferral = args.TaskInstance.GetDeferral(); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; Connection = details.AppServiceConnection; // Inform the SamplePage instance that we have been activated so it can hook up the // Connection event handlers to its methods. SamplePage.Current?.RegisterConnection(); } }
public CortanaBackgroundService(AppServiceTriggerDetails triggerDetails, BackgroundTaskDeferral serviceDeferral) { if (serviceDeferral == null) { throw new ArgumentNullException(nameof(serviceDeferral)); } this.triggerDetails = triggerDetails; this.serviceDeferral = serviceDeferral; this.commands = new List <CortanaBackgroundCommandBase> { new HowManyTasksTodayCortanaBackgroundCommand(), new AddTaskCortanaBackgroundCommand() }; }
public static async Task <ASConnection> AcceptConnectionAsync(AppServiceTriggerDetails e, BackgroundTaskDeferral connectionDeferral, IObjectSerializer serializer) { // Receive connection request, send connection response AppServiceRequest request = null; AppServiceDeferral deferral = null; var gotRequest = new SemaphoreSlim(0); e.AppServiceConnection.RequestReceived += OnRequestReceived; await gotRequest.WaitAsync(); e.AppServiceConnection.RequestReceived -= OnRequestReceived; var message = serializer.DeserializeFromValueSet(request.Message); if (message is ConnectionRequestMessage connectionRequest) { // Accept connection request var connectionId = "AS_" + Guid.NewGuid(); var connectionResponse = new ConnectionResponseMessage(connectionId); await request.SendResponseAsync(serializer.SerializeToValueSet(connectionResponse)); deferral.Complete(); return(new ASConnection( connectionId, e.AppServiceConnection, connectionDeferral, e.IsRemoteSystemConnection, serializer)); } else { // Wrong message received => reject connection var connectionResponse = new ConnectionResponseMessage(null); await request.SendResponseAsync(serializer.SerializeToValueSet(connectionResponse)); deferral.Complete(); connectionDeferral.Complete(); e.AppServiceConnection.Dispose(); return(null); } void OnRequestReceived(AppServiceConnection _, AppServiceRequestReceivedEventArgs r) { request = r.Request; deferral = r.GetDeferral(); gotRequest.Release(); } }
/// <summary> /// Invoked when the application is launched to handle background task. /// </summary> /// <param name="args">Details about the launch request.</param> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; if (details != null) { // Hold deferral reference to make sure AppService connection is always alive appServiceDeferral = args.TaskInstance.GetDeferral(); connection = details.AppServiceConnection; // Notify that connection between app and desktop server has been built AppServiceConnected?.Invoke(this, null); } }
/// <summary> /// The background task entrypoint. /// /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user /// input). There is no execution time limit on the background task managed by Cortana, /// but developers should use plmdebug (https://msdn.microsoft.com/library/windows/hardware/jj680085%28v=vs.85%29.aspx) /// on the Cortana app package in order to prevent Cortana timing out the task during /// debugging. /// /// The Cortana UI is dismissed if Cortana loses focus. /// The background task is also dismissed even if being debugged. /// Use of Remote Debugging is recommended in order to debug background task behaviors. /// Open the project properties for the app package (not the background task project), /// and enable Debug -> "Do not launch, but debug my code when it starts". /// Alternatively, add a long initial progress screen, and attach to the background task process while it executes. /// </summary> /// <param name="taskInstance">Connection to the hosting background service process.</param> public async void Run(IBackgroundTaskInstance taskInstance) { // Create the deferral by requesting it from the task instance serviceDeferral = taskInstance.GetDeferral(); AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails != null && triggerDetails.Name.Equals("VitWifiVoiceCommandService")) { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Perform the appropriate command depending on the operation defined in VCD switch (voiceCommand.CommandName) { case "Login": string x = NetworkNames.ToString(); VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage(); userMessage.DisplayMessage = string.Format("The current networks is {0} ", x); userMessage.SpokenMessage = string.Format("The current networks is {0} ", x); VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null); await voiceServiceConnection.ReportSuccessAsync(response); break; case "Logout": string logoutMessage = NetworkNames.ToString(); VoiceCommandUserMessage userLogoutMessage = new VoiceCommandUserMessage(); userLogoutMessage.DisplayMessage = string.Format("The current networks is {0} ", logoutMessage); userLogoutMessage.SpokenMessage = string.Format("The current networks is {0} ", logoutMessage); VoiceCommandResponse logoutResponse = VoiceCommandResponse.CreateResponse(userLogoutMessage, null); await voiceServiceConnection.ReportSuccessAsync(logoutResponse); break; default: break; } } // Once the asynchronous method(s) are done, close the deferral serviceDeferral.Complete(); }
public async void Run(IBackgroundTaskInstance taskInstance) { if (taskInstance.TriggerDetails is AppServiceTriggerDetails) { AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (appService.CallerPackageFamilyName == Windows.ApplicationModel.Package.Current.Id.FamilyName) // App service connection from Centennial App { this.centennialAppServiceDeferral = taskInstance.GetDeferral(); // Get a deferral so that the service isn't terminated. taskInstance.Canceled += OnCentennialAppServicesCanceled; // Associate a cancellation handler with the background task. this.centennialConnection = appService.AppServiceConnection; this.centennialConnection.RequestReceived += OnCentennialAppServiceRequestReceived; this.centennialConnection.ServiceClosed += CentennialAppServiceConnection_ServiceClosed; this.centennialConnection.AppServiceName = centennialConnectionIndex.ToString(); centennialConnections.Add(centennialConnectionIndex, this.centennialConnection); centennialAppServiceDeferrals.Add(centennialConnectionIndex, this.centennialAppServiceDeferral); centennialConnectionIndex++; } else // App service connection from Edge browser { this.appServiceDeferral = taskInstance.GetDeferral(); // Get a deferral so that the service isn't terminated. taskInstance.Canceled += OnAppServicesCanceled; // Associate a cancellation handler with the background task. this.connection = appService.AppServiceConnection; this.connection.RequestReceived += OnAppServiceRequestReceived; this.connection.ServiceClosed += AppServiceConnection_ServiceClosed; this.connection.AppServiceName = connectionIndex.ToString(); connections.Add(connectionIndex, this.connection); appServiceDeferrals.Add(connectionIndex, this.appServiceDeferral); connectionIndex++; try { // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } catch (Exception) { this.centennialAppLaunched = false; MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder"); await dialog.ShowAsync(); } } } }
/// <summary> /// Helper method for initalizing the voice service, bridge, and lights. Returns if successful. /// </summary> private async Task<bool> InitializeAsync(AppServiceTriggerDetails triggerDetails) { _voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); _voiceServiceConnection.VoiceCommandCompleted += (s, e) => _deferral.Complete(); _voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync(); _colors = HsbColor.CreateAll().ToDictionary(x => x.Name); var localStorage = ApplicationData.Current.LocalSettings.Values; _bridge = new Bridge( localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString()); try { _lights = await _bridge.GetLightsAsync(); } catch (Exception) { var response = CreateCortanaResponse("Sorry, I couldn't connect to your bridge."); await _voiceServiceConnection.ReportFailureAsync(response); return false; } if (!_lights.Any()) { var response = CreateCortanaResponse("Sorry, I couldn't find any lights."); await _voiceServiceConnection.ReportFailureAsync(response); return false; } return true; }