Calling VoiceCommandDefinitionManager Causes Thread Execution to Stop - voice

I'm totally at a loss. When I call either:
var a = VoiceCommandDefinitionManager.InstalledCommandDefinitions;
OR
await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager
.InstallCommandDefinitionsFromStorageFileAsync( storageFile );
Execution of the thread ends inside either call.
For example, in the following method after calling InstallCommandDefinitionsFromStorageFilesAsync nothing happens. No exception, no write lines, no execution after calling that method.
private async void RegisterVoiceCommands()
{
var storageFile =
await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync( new Uri( "ms-appx:///VoiceCommandDefinition.xml" ) );
try
{
await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync( storageFile );
Debug.WriteLine( "Voice Commands Registered" );
}
catch ( Exception ex )
{
Debug.WriteLine( ex );
}
}
Does anyone have any ideas? This used to work in the Technical Preview.
ENVIRONMENT:
Win 10 Enterprise
VS2015 Enterprise

So it turns out in my case it's a machine issue. The project works correctly on every other box I tried it on. Bad install I guess.

Related

Quartz.NET Runtime Scheduler will only get db connection string from app.config

I've created an asp.net core web app with Quartz for my job scheduling. I'm writing the job blueprints into a db at startup and then adding triggers and scheduling the job once I have all the info I need(user input).
Yesterday I had this issue, that Quartz couldn't find the job in the jobstore when I tried to schedule it. Eventually I figured out that it was looking in the RAM jobstore for some reason.
I tried a number of different things, did some googling to make sure I had everything setup correctly and in the end, on a whim, I figured I'd try adding the connection strings in an app.config. Suddenly quartz happily fetched the connection strings and scheduled my jobs. I added the app.config because I initially used the app.config for my connection strings when setting up the project before figuring out that using the appsettings.json is the preferred method for a .net core project. So maybe there is some setting somewhere that still prompts quartz to look for an app.config? I just have no clue where that could be.
Also, as I said, when setting up the jobs in my program.cs it gets the strings from appsettings.json just as it is supposed to.
program.cs with a most .AddJob omitted for brevity.
Log.Logger = new LoggerConfiguration().Enrich.FromLogContext().WriteTo.Console().CreateLogger();
builder.Services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionJobFactory();
var jobKey = new JobKey("HR First Contact", "DEFAULT");
q.AddJob<MailHRNewEmployee>(jobKey, j => j
.StoreDurably()
.WithDescription("job blueprint"));
q.UsePersistentStore(s =>
{
// s.PerformSchemaValidation = true;
s.UseProperties = true;
s.RetryInterval = TimeSpan.FromSeconds(15);
s.UseMySqlConnector(MySql =>
{
MySql.ConnectionString = builder.Configuration.GetConnectionString("quartz.dataSource.default.connectionString");
MySql.TablePrefix = "QRTZ_";
});
s.UseJsonSerializer();
});
});
builder.Services.Configure<QuartzOptions>(builder.Configuration.GetSection("Quartz"));
builder.Services.Configure<QuartzOptions>(options =>
{
options.Scheduling.IgnoreDuplicates = true;
options.Scheduling.OverWriteExistingData = true;
});
builder.Services.AddQuartzHostedService(options =>
{
options.WaitForJobsToComplete = true;
});
my Scheduler - most of it omitted for brevity, I can add the rest but it's just fetching data I need for the jobmap.
public async Task StartAsync(CancellationToken cancellationToken)
{
ISchedulerFactory schedFact = new StdSchedulerFactory();
this.scheduler = await schedFact.GetScheduler();
ITrigger jtriggz = CreateTriggerFirstContact();
await scheduler.ScheduleJob(jtriggz, cancellationToken);
await scheduler.Start(cancellationToken);
}
private ITrigger CreateTriggerFirstContact()
{
return Quartz.TriggerBuilder.Create().WithIdentity(_employee.FName + _employee.LName, "HR Contact").UsingJobData("FName", _employee.FName).UsingJobData("LName", _employee.LName).UsingJobData("Gender", _employee.Gender).UsingJobData("Id", Convert.ToString(_employee.Id)).UsingJobData("Empfaenger", recipient).UsingJobData("EmpfaengerName", HRManager.Name).UsingJobData("EmpfaengerGeschlecht", HRManager.Gender).StartAt(DateTime.Now.AddSeconds(10)).ForJob("HR First Contact").Build();
}

Parallel httprequest in UWP app

I'm creating an app that requires todo parallel http request, I'm using HttpClient for this.
I'm looping over the urls and foreach URl I start a new Task todo the request.
after the loop I wait untill every task finishes.
However when I check the calls being made with fiddler I see that the request are being called synchronously. It's not like a bunch of request are being made, but one by one.
I've searched for a solution and found that other people have experienced this too, but not with UWP. The solution was to increase the DefaultConnectionLimit on the ServicePointManager.
The problem is that ServicePointManager does not exist for UWP. I've looked in the API's and I thought I could set the DefaultConnectionLimit on HttpClientHandler, but no.
So I have a few Questions.
Is DefaultConnectionLimit still a property that could be set somewhere?
if so, where do i set it?
if not, how do I increase the connnectionlimit?
Is there still a connectionlimit in UWP?
this is my code:
var requests = new List<Task>();
var client = GetHttpClient();
foreach (var show in shows)
{
requests.Add(Task.Factory.StartNew((x) =>
{
((Show)x).NextEpisode = GetEpisodeAsync(((Show)x).NextEpisodeUri, client).Result;}, show));
}
}
await Task.WhenAll(requests.ToArray());
and this is the request:
public async Task<Episode> GetEpisodeAsync(string nextEpisodeUri, HttpClient client)
{
try
{
if (String.IsNullOrWhiteSpace(nextEpisodeUri)) return null;
HttpResponseMessage content; = await client.GetAsync(nextEpisodeUri);
if (content.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<EpisodeWrapper>(await content.Content.ReadAsStringAsync()).Episode;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return null;
}
Oke. I have the solution. I do need to use async/await inside the task. The problem was the fact I was using StartNew instead of Run. but I have to use StartNew because i'm passing along a state.
With the StartNew. The task inside the task is not awaited for unless you call Unwrap. So Task.StartNew(.....).Unwrap(). This way the Task.WhenAll() will wait untill the inner task is complete.
When u are using Task.Run() you don't have to do this.
Task.Run vs Task.StartNew
The stackoverflow answer
var requests = new List<Task>();
var client = GetHttpClient();
foreach (var show in shows)
{
requests.Add(Task.Factory.StartNew(async (x) =>
{
((Show)x).NextEpisode = await GetEpisodeAsync(((Show)x).NextEpisodeUri, client);
}, show)
.Unwrap());
}
Task.WaitAll(requests.ToArray());
I think an easier way to solve this is not "manually" starting requests but instead using linq with an async delegate to query the episodes and then set them afterwards.
You basically make it a two step process:
Get all next episodes
Set them in the for each
This also has the benefit of decoupling your querying code with the sideeffect of setting the show.
var shows = Enumerable.Range(0, 10).Select(x => new Show());
var client = new HttpClient();
(Show, Episode)[] nextEpisodes = await Task.WhenAll(shows
.Select(async show =>
(show, await GetEpisodeAsync(show.NextEpisodeUri, client))));
foreach ((Show Show, Episode Episode) tuple in nextEpisodes)
{
tuple.Show.NextEpisode = tuple.Episode;
}
Note that i am using the new Tuple syntax of C#7. Change to the old tuple syntax accordingly if it is not available.

Using speech synthesizer in ASP.NET web application gets stuck

In an MVC web application I use the SpeechSynthesizer class to speak some text to a .wav file during a function called by a controller action handler that returns a view. The code executes, writes the file, and the action handle returns, but the development server usually, but not always, never comes back with the return page. This is the text-to-speech code:
string threadMessage = null;
bool returnValue = true;
var t = new System.Threading.Thread(() =>
{
try
{
SpeechEngine.SetOutputToWaveFile(wavFilePath);
SpeechEngine.Speak(text);
SpeechEngine.SetOutputToNull();
}
catch (Exception exception)
{
threadMessage = "Error doing text to speech to file: " + exception.Message;
returnValue = false;
}
});
t.Start();
t.Join();
if (!returnValue)
{
message = threadMessage;
return returnValue;
}
I saw a couple of posts for a similar problem in a service that advised doing the operation in a thread, hence the above thread.
Actually, using the SpeechSynthesizer for other things can hang as well. I had a page that just enumerated the voices, but it would get stuck as well. Since there is no user code in any of the threads if I pause the debugger, I have no clue how to debug it.
I've tried Dispose'ing the SpeechSynthesizer object afterwards, calling SetOutputToDefaultVoice, to no avail. I've tried it on both Windows 8.1 and Windows 8, running with the development server under the debugger, or running IIS Express separately.
Any ideas? Is there other information I could give that would be helpful?
Thanks.
-John
Try
Public void Speak(string wavFilePath, string text)
{
using (var synthesizer = new SpeechSynthesizer())
{
synthesizer.SetOutputToWaveFile(wavFilePath);
synthesizer.Speak(text);
return outputFile;
}
}
Task.Run(() => Speak("path", "text")).Result;
It worked for me in IIS Express

Asp.Net : executionTimeout + parallel thread

On a webpage, I launche a parallel process to do a long running task then send an email to keep track of its "output".
But the thread sometimes seems to end before sending the email (the email is the only track Ihave) and I think it might be related to a timeout.
Here the code:
var thread = new Thread(() =>
{
var cli = Factory.GetClient(callBack);
FedDBService.ReturnMessage msg;
try
{
msg = cli.SendFedCards(xmls.ToArray());
}
catch (Exception exe)
{
msg = new FedDBService.ReturnMessage();
msg.Error = exe.Message;
}
finally
{
cli.Close();
completion.Finished = true;
}
message = String.Format(#"{0}Ended: {1: HH:mm} {2} {3}", message, DateTime.Now,
msg.Error.Trim(' ', '\n', '\r', '\t') == "" ?
"Withouth errors" : "With errors:"
, msg.Error);
try
{
golf.classes.Mailing.Mail.sendMail(Club.ClubEmail, email, null,
"***#***.com", message, "**Subject**", false);
// this method works right
}
finally
{
Thread.Sleep(5 * 60 * 1000);
RemoveCompletion(guid);
}
});
thread.Start();
Do you think it's related to some timeout? And can I change it withouth allowing usual requests to run forever?
You shouldn't start background work in a web app - if the App Pool is recycled, your background work will be aborted with extreme predjudice.
Phil Haack wrote a blog about this topic here:
The Dangers of Implementing Recurring Background Tasks In ASP.NET
The recommended solution is to pass this work to a seperate Windows Service.

Parallel exceptions are being caught

somehow my exceptions seem to being caught by method they are executing in. Here is the code to call the method. As you can see I create a cancellation token with a time out. I register a method to call when the cancellation token fires and then I start a new task. The cancellation token appears to be working OK. As does the registered method.
var cancellationToken = new CancellationTokenSource(subscriber.TimeToExpire).Token;
cancellationToken.Register(() =>
{
subscriber.Abort();
});
var task = Task<bool>.Factory.StartNew(() =>
{
subscriber.RunAsync((T)messagePacket.Body, cancellationToken);
return true;
})
.ContinueWith(anticedant =>
{
if (anticedant.IsCanceled)
{
Counter.Increment(12);
Trace.WriteLine("Request was canceled");
}
if (anticedant.IsFaulted)
{
Counter.Increment(13);
Trace.WriteLine("Request was canceled");
}
if (anticedant.IsCompleted)
{
Counter.Increment(14);
}
The next piece of code is the method that seems to be not only throwing the excetion (expected behavior. but also catching the exception.
public async override Task<bool> ProcessAsync(Message input, CancellationToken cancellationToken)
{
Random r = new Random();
Thread.Sleep(r.Next(90, 110));
cancellationToken.ThrowIfCancellationRequested();
return await DoSomethingAsync(input);
}
The exception is being thrown by the cancellation token but according to intellitrace it is being caught at the end of the method. I have tried a number of different options including throwing my own exception, but no matter what the continuewith function always executes the IsComleted or ran to completion code.
Any ideas on what I am doing wrong?
Thanks
I assume that RunAsync is the same as ProcessAsync.
The exception is being thrown by the cancellation token but according to intellitrace it is being caught at the end of the method.
Yup. Any async method will catch its own exceptions and place them on its returned Task. This is by design.
no matter what the continuewith function always executes the IsComleted or ran to completion code.
Well, let's take another look at the code:
var task = Task<bool>.Factory.StartNew(() =>
{
subscriber.RunAsync((T)messagePacket.Body, cancellationToken);
return true;
})
.ContinueWith(
Consider the lambda passed to StartNew: it calls RunAsync, it ignores the Task that it returns, and then it returns true (successfully). So the Task returned by StartNew will always return successfully. This is why the ContinueWith always executes for a successfully-completed task.
What you really want is to await the Task returned by RunAsync. So, something like this:
var task = Task.Run(async () =>
{
await subscriber.RunAsync((T)messagePacket.Body, cancellationToken);
return true;
})
.ContinueWith(
You're still ignoring the return value of RunAsync (the bool it returns is ignored), but you're not ignoring the Task itself (including cancellation/exception information).
P.S. I'm assuming there's a lot of code you're not showing us; using StartNew/Run to just kick off some async work and return a value is very expensive.
P.P.S. Use await Task.Delay instead of Thread.Sleep.

Resources