SetPhraseListAsync — катастрофический сбой

Я пытаюсь обновить списки фраз своего приложения UWP (Windows 10), но больше, чем нет, я получаю «катастрофический сбой» без объяснения причин.

Я регистрирую Cortana так в App.xaml.cs

StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"VoiceCommandDefinition.xml");
await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile);
Debug.WriteLine("Cortana loaded");

Затем я загружаю свои данные (это клиент термостата Nest, поэтому я загружаю термостаты и конструкции). После этого я пытаюсь обновить списки фраз.

string thermostatsStrings = "";
string structureStrings = "";
VoiceCommandDefinition commandSetEnUs;
if (VoiceCommandDefinitionManager.InstalledCommandDefinitions.TryGetValue("Nest_en-us", out commandSetEnUs))
{
    try
    {
        List<Nest.Thermostat> thermostats = GetAllThermostats();
        if (thermostats != null)
        {
            thermostatsStrings = String.Join(", ", thermostats);
            List<String> names = thermostats.Select(thermostat => thermostat.name).ToList();
            await commandSetEnUs.SetPhraseListAsync("nest", names);
        }
    }
    catch (Exception ex)
    {
        Crashes.Log("Helpers - UpdatePhraseListThermostat", true, ex.Message + 
            Environment.NewLine + "Thermostats: " + thermostatsStrings + 
            Environment.NewLine + "Structures: " + structureStrings);
    }
    try
    {
        List<Nest.Structure> structures = GetAllStructures();
        if (structures != null)
        {
            structureStrings = String.Join(", ", structures);
            List<String> names = structures.Select(structure => structure.name).ToList();
            await commandSetEnUs.SetPhraseListAsync("place", names);
        }
    }
    catch (Exception ex)
    {
        Crashes.Log("Helpers - UpdatePhraseListStructure", true, ex.Message +
            Environment.NewLine + "Thermostats: " + thermostatsStrings +
            Environment.NewLine + "Structures: " + structureStrings);
    }
}

Мой файл VCD выглядит так

<?xml version="1.0" encoding="utf-8" ?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
<CommandSet xml:lang="en-US" Name="Nest_en-us">
<AppName> Nest </AppName>
<Example> Open Nest </Example>

<Command Name="RequestTemp">
  <Example>Nest, what is the current temperature </Example>
  <ListenFor> What is [the] {nest} temperature </ListenFor>
  <ListenFor> What is [the] temperature in the {nest} </ListenFor>
  <ListenFor> What is [the] [current] temperature </ListenFor>
  <Feedback> Getting the temperature </Feedback>
  <VoiceCommandService Target="NestCommandService"/>
</Command>

<Command Name="SetHome">
  <Example> Nest, I'm coming home </Example>
  <ListenFor> Set {place} to home </ListenFor>
  <ListenFor> I am on my way to {place} </ListenFor>
  <ListenFor> I am coming home </ListenFor>
  <ListenFor> I am home </ListenFor>
  <ListenFor> set [status] to home </ListenFor>
  <ListenFor> set [state] to home </ListenFor>
  <ListenFor> set [mode] to home </ListenFor>
  <ListenFor> I am back </ListenFor>
  <ListenFor> I am on my way [home] </ListenFor>


  <Feedback> Setting mode to home </Feedback>
  <VoiceCommandService Target="NestCommandService"/>
</Command>


<PhraseList Label="nest">

</PhraseList>

<PhraseList Label="place">

</PhraseList>

</CommandSet>
</VoiceCommands>

Я встроил журнал ошибок в свое приложение (MetroLog), вот что он регистрирует:

2|2016-02-03T15:39:14.0034437+00:00|TRACE|2|Crashes|Helpers - UpdatePhraseListThermostat
Catastrophic failure

Catastrophic failure

Thermostats: Living Room
Structures: 
3|2016-02-03T16:03:32.2687198+00:00|TRACE|2|Crashes|Helpers - UpdatePhraseListStructure
Catastrophic failure

Catastrophic failure

Thermostats: Living Room
Structures: Home

person vixez    schedule 11.02.2016    source источник


Ответы (1)


В коде есть пара ошибок. Во-первых, если вы пытаетесь установить VCD из пакета приложения, код выглядит примерно так:

Uri uriVoiceCommands = new Uri("ms-appx:///VoiceCommandDefinition1.xml", UriKind.Absolute);
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uriVoiceCommands);
        await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(file);

Во-вторых, при объявлении списка фраз не рекомендуется не вставлять ни один элемент внутрь списка фраз, поэтому изначально вы должны поставить хотя бы 1 элемент. В-третьих, Катастрофическая ошибка, возможно, связана с тем, что у вас выполняется много кода для определения обновления VCD, я бы предпочел определить значения, которые должны быть помещены в список фраз, в отдельном методе, а затем использовать следующий код для обновления список фраз динамически:

Windows.Media.SpeechRecognition.VoiceCommandSet commandSetEnUs;

    if (Windows.Media.SpeechRecognition.VoiceCommandManager.InstalledCommandSets.TryGetValue("AdventureWorksCommandSet_en-us", out commandSetEnUs))
    {
        await commandSetEnUs.SetPhraseListAsync(
          "destination", new string[] { Value1Det, value2Det });   //where Value2Det and Value1Det are the resulted outputs from thermostat 
    }
person iam.Carrot    schedule 21.02.2016