My idea is I can define a block of code (inline) that corresponds to an input string
then can call that block of code when given that input.
I'm used to this sort of structure in JavaScript like so:
var lookup = {
"foo": function() { ... },
"bar": function() { ... },
};
lookup["foo"];
And I'm looking for a C# equivalent. So far I've come up with the following and it seems to work, but I don't know if it could be simplified or improved upon.
class CortanaFunctions
{
/*
This is the lookup of VCD CommandNames as defined in
CustomVoiceCommandDefinitios.xml to their corresponding actions
*/
public readonly static Dictionary<string, Delegate> vcdLookup = new Dictionary<string, Delegate>{
/*
{<command name from VCD>, (Action)(async () => {
<code that runs when that commmand is called>
})}
*/
{"OpenToDoList", (Action)(async () => {
StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ToDo.doc");
await Launcher.LaunchFileAsync(file);
})},
{"OpenReddit", (Action)(async () => {
Uri website = new Uri(@"http://www.reddit.com");
await Launcher.LaunchUriAsync(website);
})},
};
/*
Register Custom Cortana Commands from VCD file
*/
public static async void RegisterVCD()
{
StorageFile vcd = await Package.Current.InstalledLocation.GetFileAsync(
@"CustomVoiceCommandDefinitions.xml");
await VoiceCommandDefinitionManager
.InstallCommandDefinitionsFromStorageFileAsync(vcd);
}
/*
Look up the spoken command and execute its corresponding action
*/
public static void RunCommand(VoiceCommandActivatedEventArgs cmd)
{
SpeechRecognitionResult result = cmd.Result;
string commandName = result.RulePath[0];
vcdLookup[commandName].DynamicInvoke();
}
}
VCD file:
<?xml version="1.0" encoding="utf-8" ?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
<CommandSet xml:lang="en-us" Name="CustomCommands">
<CommandPrefix> listen here </CommandPrefix>
<Example> open to do list, open reddit</Example>
<Command Name="OpenToDoList">
<Example> open to do list </Example>
<ListenFor> open to do list</ListenFor>
<Feedback> opening your to do list</Feedback>
<Navigate/>
</Command>
<Command Name="OpenReddit">
<Example> open reddit </Example>
<ListenFor> open reddit </ListenFor>
<Feedback> opening reddit </Feedback>
<Navigate/>
</Command>
</CommandSet>
</VoiceCommands>