/// <summary> /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="..."> /// tag will invoke this when they are recognized by Cortana, passing along details of the /// invocation. /// /// 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/en-us/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. /// /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background /// task, even if the background task is being debugged. Use of Remote Debugging is recommended /// in order to debug background task behaviors. In order to debug background tasks, 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) { serviceDeferral = taskInstance.GetDeferral(); // Register to receive an event if Cortana dismisses the background task. This will // occur if the task takes too long to respond, or if Cortana's UI is dismissed. // Any pending operations should be cancelled or waited on to clean up where possible. taskInstance.Canceled += OnTaskCanceled; var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; // Load localized resources for strings sent to Cortana to be displayed to the user. cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); // Select the system language, which is what Cortana should be running as. cortanaContext = ResourceContext.GetForViewIndependentUse(); // Get the currently used system date format dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat; // This should match the uap:AppService and VoiceCommandService references from the // package manifest and VCD files, respectively. Make sure we've been launched by // a Cortana Voice Command. if (triggerDetails != null && triggerDetails.Name == "AdventureWorksVoiceCommandService") { try { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails( triggerDetails); voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted; // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc // prior to calling this will produce undefined behavior. VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml) // perform the appropriate command. 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 ResourceManagerImpl(string resourceName) { this.resourceName = resourceName; this.stringResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Microsoft.Azure.Amqp/" + resourceName); this.resourceContext = ResourceContext.GetForViewIndependentUse(); }
public ResourceManagerImpl() { stringResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Microsoft.Azure.Devices.Client.UWP/Resources"); resourceContext = ResourceContext.GetForViewIndependentUse(); }
private async void Scenario12Button_Show_Click(object sender, RoutedEventArgs e) { // Two coding patterns will be used: // 1. Get a ResourceContext on the UI thread using GetForCurrentView and pass // to the non-UI thread // 2. Get a ResourceContext on the non-UI thread using GetForViewIndependentUse // // Two analogous patterns could be used for ResourceLoader instead of ResourceContext. // pattern 1: get a ResourceContext for the UI thread ResourceContext defaultContextForUiThread = ResourceContext.GetForCurrentView(); // pattern 2: we'll create a view-independent context in the non-UI worker thread // We need some things in order to display results in the UI (doing that // for purposes of this sample, to show that work was actually done in the // worker thread): List <string> uiDependentResourceList = new List <string>(); List <string> uiIndependentResourceList = new List <string>(); // use a worker thread for the heavy lifting so the UI isn't blocked await Windows.System.Threading.ThreadPool.RunAsync( (source) => { ResourceMap stringResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); // pattern 1: the defaultContextForUiThread variable was created above and is visible here // pattern 2: get a view-independent ResourceContext ResourceContext defaultViewIndependentResourceContext = ResourceContext.GetForViewIndependentUse(); // NOTE: The ResourceContext obtained using GetForViewIndependentUse() has no scale qualifier // value set. If this ResourceContext is used in its default state to retrieve a resource, that // will work provided that the resource does not have any scale-qualified variants. But if the // resource has any scale-qualified variants, then that will fail at runtime. // // A scale qualifier value on this ResourceContext can be set programmatically. If that is done, // then the ResourceContext can be used to retrieve a resource that has scale-qualified variants. // But if the scale qualifier is reset (e.g., using the ResourceContext.Reset() method), then // it will return to the default state with no scale qualifier value set, and cannot be used // to retrieve any resource that has scale-qualified variants. // simulate processing a number of items // just using a single string resource: that's sufficient to demonstrate for (var i = 0; i < 4; i++) { // pattern 1: use the ResourceContext from the UI thread string listItem1 = stringResourceMap.GetValue("string1", defaultContextForUiThread).ValueAsString; uiDependentResourceList.Add(listItem1); // pattern 2: use the view-independent ResourceContext string listItem2 = stringResourceMap.GetValue("string1", defaultViewIndependentResourceContext).ValueAsString; uiIndependentResourceList.Add(listItem2); } }); // Display the results in one go. (A more finessed design might add results // in the UI asynchronously, but that goes beyond what this sample is // demonstrating.) ViewDependentResourcesList.ItemsSource = uiDependentResourceList; ViewIndependentResourcesList.ItemsSource = uiIndependentResourceList; }
//this function will be invoked when calling a VoiceCommand with the <VoiceCommandService Target="..."> //tag public async void Run(IBackgroundTaskInstance taskInstance) { serviceDeferral = taskInstance.GetDeferral(); //register an event if cortana dismisses the background task taskInstance.Canceled += OnTaskCanceled; var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; // Load localized resources for strings sent to Cortana to be displayed to the user. cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); // Select the system language, which is what Cortana should be running as. cortanaContext = ResourceContext.GetForViewIndependentUse(); // This should match the uap:AppService and VoiceCommandService references from the // package manifest and VCD files, respectively. Make sure we've been launched by // a Cortana Voice Command. if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService") { try { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails( triggerDetails); voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted; // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc // prior to calling this will produce undefined behavior. VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml) // perform the appropriate command. switch (voiceCommand.CommandName) { case "showPastPopulation": var pastCountry = voiceCommand.Properties["country"][0]; var pastYear = voiceCommand.Properties["year"][0]; //search type is the whole population string pastSearchType = "\"Population. total\""; await SendCompletionMessageForPastPopulation(pastCountry, pastYear, pastSearchType); break; case "showPastWomenPercentage": var pastWomenCountry = voiceCommand.Properties["country"][0]; var pastWomenYear = voiceCommand.Properties["year"][0]; //search type is the whole population string womenSearchType = "\"Population. female (% of total)\""; await SendCompletionMessageForPastWomenProportion(pastWomenCountry, pastWomenYear, womenSearchType); break; case "showFuturePopulation": var futureCountry = voiceCommand.Properties["country"][0]; var futureYear = voiceCommand.Properties["year"][0]; await SendCompletionMessageForFuturePopulation(futureCountry, futureYear); break; case "showFuturePopulationML": var futureYearML = voiceCommand.Properties["year"][0]; await SendCompletionMessageForFuturePopulationML(futureYearML); break; default: break; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString()); } } }
private async void CreateResourceContext() { var currentResourceManager = ResourceManager.Current; var resourceContext1 = ResourceContext.GetForViewIndependentUse(); var resourceContext2 = ResourceContext.GetForCurrentView(); }
public Resources() { ResourceContext = ResourceContext.GetForViewIndependentUse(); ResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); }
/// <summary> /// Gets the string from the specified resource file with the current culture. /// </summary> /// <param name="languageSource">The language source.</param> /// <param name="resourceName">Name of the resource.</param> /// <param name="cultureInfo">The culture information.</param> /// <returns>The string or <c>null</c> if the string cannot be found.</returns> /// <exception cref="ArgumentNullException">The <paramref name="languageSource" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException">The <paramref name="resourceName" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="cultureInfo" /> is <c>null</c>.</exception> public override string GetString(ILanguageSource languageSource, string resourceName, CultureInfo cultureInfo) { Argument.IsNotNull("languageSource", languageSource); Argument.IsNotNullOrWhitespace("resourceName", resourceName); Argument.IsNotNull("cultureInfo", cultureInfo); string value = null; var source = languageSource.GetSource(); var resourceLoader = GetResourceManager(source); if (resourceLoader != null) { #if NETFX_CORE var resourceContainer = GetResourceContainer(source); // Try the language specific first var neutralSource = string.Format("{0}", resourceContainer); var cultureName = cultureInfo.Name; var languageSpecificSource = string.Format("{0}.{1}", resourceContainer, cultureName); var currentResourceManager = Windows.ApplicationModel.Resources.Core.ResourceManager.Current; var finalResourceMap = (from resourceMap in currentResourceManager.AllResourceMaps let rm = resourceMap.Value.GetSubtree(languageSpecificSource) where rm != null select rm).FirstOrDefault(); if ((finalResourceMap == null) && !cultureInfo.IsNeutralCulture) { cultureName = cultureInfo.Parent.Name; languageSpecificSource = string.Format("{0}.{1}", resourceContainer, cultureName); finalResourceMap = (from resourceMap in currentResourceManager.AllResourceMaps let rm = resourceMap.Value.GetSubtree(languageSpecificSource) where rm != null select rm).FirstOrDefault(); } if (finalResourceMap == null) { finalResourceMap = (from resourceMap in currentResourceManager.AllResourceMaps let rm = resourceMap.Value.GetSubtree(neutralSource) where rm != null select rm).FirstOrDefault(); } if (finalResourceMap != null) { var resourceContext = ResourceContext.GetForViewIndependentUse(); resourceContext.Languages = new[] { cultureName }; var resourceCandidate = finalResourceMap.GetValue(resourceName, resourceContext); if (resourceCandidate != null) { value = resourceCandidate.ValueAsString; } } #else value = resourceLoader.GetString(resourceName, cultureInfo); #endif } return(value); }
public async void Run(IBackgroundTaskInstance taskInstance) { serviceDeferral = taskInstance.GetDeferral(); // Register to receive an event if Cortana dismisses the background task. This will // occur if the task takes too long to respond, or if Cortana's UI is dismissed. // Any pending operations should be cancelled or waited on to clean up where possible. taskInstance.Canceled += OnTaskCanceled; var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; // Load localized resources for strings sent to Cortana to be displayed to the user. cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); // Select the system language, which is what Cortana should be running as. cortanaContext = ResourceContext.GetForViewIndependentUse(); // Get the currently used system date format dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat; // This should match the uap:AppService and VoiceCommandService references from the // package manifest and VCD files, respectively. Make sure we've been launched by // a Cortana Voice Command. if (triggerDetails != null && triggerDetails.Name == "MyDevPalBackgroundTask") { try { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails( triggerDetails); voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted; // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc // prior to calling this will produce undefined behavior. VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml) // perform the appropriate command. switch (voiceCommand.CommandName) { case "readyToCode": await MessageService.SendMessage("Cortana", "I'm feelin fine!", 5, 10, 10); break; case "readyToCode1": await MessageService.SendMessage("Cortana", "I'm feeling a bit lonely!", 0, 5, -5); break; case "doneCoding": await MessageService.SendMessage("Cortana", "I'm Starting to drag!", -5, -10, -10); break; case "hungry": await MessageService.SendMessage("Cortana", "I'm hungry!", -5, -20, -5); break; case "full": await MessageService.SendMessage("Cortana", "I just ate!", 5, 20, 5); break; default: break; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString()); } } }