Unable to Run AudioGraph in Background Task - xamarin

I'm developing a Xamarin application. It's a glorified audio player. I created a background task for the UWP part which extends IBackgroundTask from Windows.ApplicationModel.Background.
using Windows.ApplicationModel.Background;
public sealed class BackgroundServiceManager : IBackgroundTask {
private IIpcNode m_node;//Sends/Receive message powered by LocalSettings
private BackgroundTaskDeferral m_deferral;
public void Run(IBackgroundTaskInstance taskInstance) {
DebugUtils.Log("BackgroundServiceManager.Run()");
m_deferral = taskInstance.GetDeferral();
m_services = new List<IBackgroundService> {
(m_playbackService = new PlaybackService()),
(m_smartLightService = new SmartLightsService())
};
this.RegisterServices();
taskInstance.Task.Completed += OnTaskCompleted;
taskInstance.Canceled += OnTaskCanceled;
//Listen to messages powered by LocalSettings
m_node.StartListening();
}
//...
}
I start the task using an application trigger. The background task lives in a separate project.
public async Task InitializeBackgroundTask() {
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values.Clear();
BackgroundExecutionManager.RemoveAccess();
var accessStatus = await BackgroundExecutionManager.RequestAccessAsync();
if (accessStatus == BackgroundAccessStatus.DeniedBySystemPolicy
|| accessStatus == BackgroundAccessStatus.DeniedByUser
|| accessStatus == BackgroundAccessStatus.Unspecified)
return;
UnregisterExistingTasks();
var builder = new BackgroundTaskBuilder() {
Name = BACKGROUND_TASK_NAME,
TaskEntryPoint = BACKGROUND_TASK_ENTRY_POINT,
};
var applicationTrigger = new ApplicationTrigger();
builder.SetTrigger(applicationTrigger);
var registration = (BackgroundTaskRegistration)null;
try {
registration = builder.Register();
}
catch (Exception ex) {
throw new Exception(string.Format("Unable to register {0} background task.", BACKGROUND_TASK_NAME), ex);
}
registration.Completed += OnBackgroundTaskCompleted;
registration.Progress += OnRegistrationProgress;
this.Node.StartListening();
var result = await applicationTrigger.RequestAsync();
if (result != ApplicationTriggerResult.Allowed)
throw new Exception("Unable to trigger background task.");
}
I have a background task declaration in my main UWP project. The task type is "general" and I provide the proper entry point.
Also, the Background Media Playback capability is checked.
The task works perfectly fine, but AudioGraph doesn't generate sounds on the background task. MediaPlayer does, however. I need AudioGraph as it allows for seamless audio looping.
Here's my AudioGraph test method. I created it to isolate AudioGraph-related code:
public static async Task TestAudioGraph(int toneFrequency) {
var audioFileInfo = await AudioUtils.CreateToneFile(toneFrequency);
var settings = new AudioGraphSettings(Windows.Media.Render.AudioRenderCategory.Media);
var createAudioGraphResult = await AudioGraph.CreateAsync(settings);
if (createAudioGraphResult.Status != AudioGraphCreationStatus.Success)
throw new Exception(createAudioGraphResult.Status.ToString());
var audioGraph = createAudioGraphResult.Graph;
var createDeviceOutputNodeResult = await audioGraph.CreateDeviceOutputNodeAsync();
if (createDeviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
throw new Exception(createDeviceOutputNodeResult.Status.ToString());
var deviceOutputNode = createDeviceOutputNodeResult.DeviceOutputNode;
var storageFile = await StorageFile.GetFileFromPathAsync(audioFileInfo.FileFullPath);
var createFileInputNodeResult = await audioGraph.CreateFileInputNodeAsync(storageFile);
if (createFileInputNodeResult.Status != AudioFileNodeCreationStatus.Success)
throw new Exception(createFileInputNodeResult.Status.ToString());
var fileInputNode = createFileInputNodeResult.FileInputNode;
fileInputNode.OutgoingGain = 1;
fileInputNode.LoopCount = Int32.MaxValue;
fileInputNode.AddOutgoingConnection(deviceOutputNode);
fileInputNode.Start();
audioGraph.Start();
await Task.Delay(3000);
}
Sending of sound test message from foreground:
public async Task TestSound() {
//Test sound on foreground first
await Task.Run(async () => await UWPUtils.TestAudioGraph(200));
var message = new UWPIpcMessage("TESTSOUND", null);
await this.Node.SendMessage(message, true);
}
Background's handling of sound test message:
m_node.Subscribe("TESTSOUND", async (message) => {
//Then test sound on background
await Task.Run(async () => await UWPUtils.TestAudioGraph(800));
return null;
});
Would you happen to know why AudioGraph doesn't work? Am I missing a setting or is this possible at all?
I look on the web and couldn't find examples or working samples, just hints that what I'm attempting is possible.
P-S: My task type is "general", because I found no way of triggering "audio" type of tasks.
Thank you

Related

Puppeteer LaunchAsync throwing exception

I have an existing ASPNET Web Application. The front end is HTML/JavaScript and the backend is WebAPI 2. We have been using NRECO.PDFGenerator to drop PDFs to the users, this uses a the QT browser and debugging is becoming a chore. I found PuppeteerSharp and figured I'd give it a try.
I installed the libs using nuget, added an Async method to one of my Web Api Controllers but when I call it the LaunchAsync method just crashed.
[Route("api/pdf/v2/download")]
public IHttpActionResult V2Download([FromBody] Models.PDF.List _pdf) {
Models.Message.Response _return = new Models.Message.Response();
_return.Message = "Success!";
_return.Now = DateTime.Now;
try
{
string[] argu = null;
Meh(argu);
}
catch (Exception ex)
{
_return.Message = ex.Message;
_return.Severity = 3;
}
return Ok(_return);
}
public static async Task Meh(string[] args)
{
var options = new LaunchOptions
{
Headless = true,
Args = new[] {"--no-sandbox" }
};
Debug.WriteLine("Downloading chromium");
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
Debug.WriteLine("Navigating google");
using (var browser = await Puppeteer.LaunchAsync(options))
using (var page = await browser.NewPageAsync())
{
Debug.WriteLine("Navigating to page");
await page.GoToAsync("http://www.google.com");
Debug.WriteLine("Generating PDF");
await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine("Export completed");
if (!args.Any(arg => arg == "auto-exit"))
{
Console.ReadLine();
}
}
}
I'm not sure where to go from here. This is the console output. There's more...
Navigating google
The thread 0x3418 has exited with code 0 (0x0).
Exception thrown: 'System.NullReferenceException' in System.Web.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
The project is using framework 4.7.2
Solution
Everything that touches the Async method needs to also be Async. Also, Passing null args will cause problems as well.
Here's a code sample.
//[Authorize]
[Route("api/pdf/v2/download")]
public async Task<IHttpActionResult> V2Download([FromBody] Models.PDF.List _pdf) {
Models.Message.Response _return = new Models.Message.Response();
_return.Message = "Success!";
_return.Now = DateTime.Now;
try
{
string[] argu = { };
await Meh(argu);
}
catch (Exception ex)
{
_return.Message = ex.Message;
_return.Severity = 3;
}
return Ok(_return);
}
public static async Task Meh(string[] args)
{
var options = new LaunchOptions
{
Headless = true
};
Debug.WriteLine("Downloading chromium");
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
Debug.WriteLine("Navigating google");
using (var browser = await Puppeteer.LaunchAsync(options))
using (var page = await browser.NewPageAsync())
{
Debug.WriteLine("Navigating to page");
await page.GoToAsync("http://www.google.com");
Debug.WriteLine("Generating PDF");
await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine("Export completed");
if (!args.Any(arg => arg == "auto-exit"))
{
Console.ReadLine();
}
}
}

Microsoft Bot Framework unit tests not continuing dialogs

I have a MSFT Bot Framework application for which I am trying to write unit tests. I have single call/response tests working fine, but anything that requires continuing a dialog does not work. The ActiveDialog property in the DialogContext that get's created on every turn is always null and the Stack property is always empty. I was sort of following this blog post example. What am I missing that allows the bot to maintain it's state between turns?
One-Time Setup
protected virtual void TestFixtureSetup()
{
var environmentName = "development";
var builder = new ConfigurationBuilder();
var configuration = builder.Build();
_connectedServices = new BotServices(_botConfig, configuration, environmentName);
_testAdapter = new TestAdapter();
_testAdapter.Use(new AutoSaveStateMiddleware());
}
Per-Test Setup
protected virtual void TestSetup()
{
var memStore = new MemoryStorage();
var userState = new UserState(memStore);
var conversationState = new ConversationState(memStore);
var dialogState = conversationState.CreateProperty<DialogState>("dialogState");
_dialogSet = new DialogSet(dialogState);
_dialogSet.Add(new MainDialog(_connectedServices, conversationState, userState, new TestTelemetryClient()));
_testFlow = new TestFlow(_testAdapter, async (turnContext, cancellationToken) =>
{
var dc = await _dialogSet.CreateContextAsync(turnContext, cancellationToken);
await dc.ContinueDialogAsync();
if (!turnContext.Responded)
{
await dc.BeginDialogAsync(nameof(MainDialog));
}
});
}
Test
public async Task MenuTestMethod(string subMenuOption, string verificationString)
{
var firstMenu = Responses.BuildFirstMenu(null, null);
var secondMenu = Responses.BuildSecondMenu(null, null);
await _testFlow
.Send("go to first menu")
.AssertReply((activity) =>
{
Assert.AreEqual(firstMenu.Attachments[0].Content, activity.AsMessageActivity().Attachments[0].Content);
})
.Send("go to second menu")
.AssertReply((activity) =>
{
Assert.AreEqual(secondMenu.Attachments[0].Content, activity.AsMessageActivity().Attachments[0].Content);
})
.Send(subMenuOption)
.AssertReply((activity) =>
{
Assert.IsTrue(activity.AsMessageActivity().Text.Contains(verificationString));
})
.StartTestAsync();
}

How to make async call to api (http). in c#. inside a Task

I am developeing a chatbot using microsoftbotframmwok where I have some requirement to make a call from my task to an api(httpclient). but it is not working. when i test the api from an stand alone console application in side main method it works. but in my application it doesn't work.
I tried to call an api from an simple method without task but when it makes a cal its basically halts or stucked somewhere, i converted my function into task and while making an api call i used await keyword to call it asynchronously but it is returning error, while reading it not the result.
here is the my code which make an api call
private async Task<String> getProblem(IDialogContext context)
{
var response = "Thannks for contacting..";
//here some code logix..
SnowApiClient client = new SnowApiClient(Url, UserId, ApiPassword);
IncidentRequestPayload payload = new IncidentRequestPayload();
payload.caller_id = "tet111";
payload.assignment_group = "it";
payload.category = "complaint";
payload.u_feedback_type = "Praise";
payload.service_offering = "Application Management";
payload.priority = 2;
payload.short_description = "computer battery is dead";
payload.comments = String.Empty;
ApiResponse objResponse = await client.CreateIncident(payload);
//objResponse.payload.number;
return response;
}
//code for CreateIncident...in Api project librarary
public async Task<ApiResponse> CreateIncident(IncidentRequestPayload payload)
{
var incidentRequest = new ApiRequest { method = CreateIncidentMethod, payload = payload };
var createResult = await ExecuteRequest(incidentRequest);
return await ReadIncident(createResult.payload.incNumber);
}
public async Task<ApiResponse> ReadIncident(string number)
{
var incidentRequest = new ApiRequest { method = ReadIncidentMethod, payload = new RequestPayload { number = number } };
return await ExecuteRequest(incidentRequest);
}
private async Task<ApiResponse> ExecuteRequest(ApiRequest requestObject)
{
HttpResponseMessage response = await _client.PostAsJsonAsync("/SRintegratedAPI.rest", requestObject);
ApiResponse responseObject = null;
if (response.IsSuccessStatusCode)
{
responseObject = await response.Content.ReadAsAsync<ApiResponse>();
}
else
{
throw new System.Net.WebException(response.ReasonPhrase);
}
if (responseObject.result != "ok")
{
throw new System.Net.WebException(responseObject.message);
}
return responseObject;
}
I don't understand how and where do i used async/await here in basicalaly in my getProblem function.
please help

Background Task is not registered and the code is not working when the application is in background

I'm using parse for sending push notification and its working perfectly but, in the background i.e., when the application is not running then the code for registering the background service is executed but, no task is set and the background task is not executed after receiving the notification. Please help!!
Here is the code for registering the background task
Debug.WriteLine("Registering task");
var taskRegistered = false;
var exampleTaskName = "BackgroundTask";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
taskRegistered = true;
task.Value.Unregister(true);
break;
}
}
await BackgroundExecutionManager.RequestAccessAsync();
if (!taskRegistered)
{
Debug.WriteLine("Registering task inside");
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Tasks.BackgroundTask";
builder.Name = "PushNotification";
builder.SetTrigger(new Windows.ApplicationModel.Background.PushNotificationTrigger());
BackgroundTaskRegistration task = builder.Register();
await BackgroundExecutionManager.RequestAccessAsync();
}
Code that is executed in the background:
public async void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("1");
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
Debug.WriteLine("2");
_deferral.Complete();
}

Azure Notification Hub and WP8 Intermitant notifications

This is a fairly long piece of code but I am getting nowhere with this and cannot see any issues, although I am new to using notification hubs. I am trying to register for targeted notifications (the logged on user) using the notification hub in Azure. After the registration, a test notification is sent.
The issue I am having is that sometimes the notification is sent to the device, and sometimes it is not. It mostly isn't but occasionally when I step through the code on the server, i will get the notification on the emulator come through. Once when I deployed the app to my phone the notification came though on the emulator! I cannot discover a pattern.
My Controller class looks like this;
private NotificationHelper hub;
public RegisterController()
{
hub = NotificationHelper.Instance;
}
public async Task<RegistrationDescription> Post([FromBody]JObject registrationCall)
{
var obj = await hub.Post(registrationCall);
return obj;
}
And the helper class (which is used elsewhere so is not directly in the controller) looks like this;
public static NotificationHelper Instance = new NotificationHelper();
public NotificationHubClient Hub { get; set; }
// Create the client in the constructor.
public NotificationHelper()
{
var cn = "<my-cn>";
Hub = NotificationHubClient.CreateClientFromConnectionString(cn, "<my-hub>");
}
public async Task<RegistrationDescription> Post([FromBody] JObject registrationCall)
{
// Get the registration info that we need from the request.
var platform = registrationCall["platform"].ToString();
var installationId = registrationCall["instId"].ToString();
var channelUri = registrationCall["channelUri"] != null
? registrationCall["channelUri"].ToString()
: null;
var deviceToken = registrationCall["deviceToken"] != null
? registrationCall["deviceToken"].ToString()
: null;
var userName = HttpContext.Current.User.Identity.Name;
// Get registrations for the current installation ID.
var regsForInstId = await Hub.GetRegistrationsByTagAsync(installationId, 100);
var updated = false;
var firstRegistration = true;
RegistrationDescription registration = null;
// Check for existing registrations.
foreach (var registrationDescription in regsForInstId)
{
if (firstRegistration)
{
// Update the tags.
registrationDescription.Tags = new HashSet<string>() {installationId, userName};
// We need to handle each platform separately.
switch (platform)
{
case "windows":
var winReg = registrationDescription as MpnsRegistrationDescription;
winReg.ChannelUri = new Uri(channelUri);
registration = await Hub.UpdateRegistrationAsync(winReg);
break;
case "ios":
var iosReg = registrationDescription as AppleRegistrationDescription;
iosReg.DeviceToken = deviceToken;
registration = await Hub.UpdateRegistrationAsync(iosReg);
break;
}
updated = true;
firstRegistration = false;
}
else
{
// We shouldn't have any extra registrations; delete if we do.
await Hub.DeleteRegistrationAsync(registrationDescription);
}
}
// Create a new registration.
if (!updated)
{
switch (platform)
{
case "windows":
registration = await Hub.CreateMpnsNativeRegistrationAsync(channelUri,
new string[] {installationId, userName});
break;
case "ios":
registration = await Hub.CreateAppleNativeRegistrationAsync(deviceToken,
new string[] {installationId, userName});
break;
}
}
// Send out a test notification.
await SendNotification(string.Format("Test notification for {0}", userName), userName);
return registration;
And finally, my SendNotification method is here;
internal async Task SendNotification(string notificationText, string tag)
{
try
{
var toast = PrepareToastPayload("<my-hub>", notificationText);
// Send a notification to the logged-in user on both platforms.
await NotificationHelper.Instance.Hub.SendMpnsNativeNotificationAsync(toast, tag);
//await hubClient.SendAppleNativeNotificationAsync(alert, tag);
}
catch (ArgumentException ex)
{
// This is expected when an APNS registration doesn't exist.
Console.WriteLine(ex.Message);
}
}
I suspect the issue is in my phone client code, which is here and SubscribeToService is called immediately after WebAPI login;
public void SubscribeToService()
{
_channel = HttpNotificationChannel.Find("mychannel");
if (_channel == null)
{
_channel = new HttpNotificationChannel("mychannel");
_channel.Open();
_channel.BindToShellToast();
}
_channel.ChannelUriUpdated += async (o, args) =>
{
var hub = new NotificationHub("<my-hub>", "<my-cn>");
await hub.RegisterNativeAsync(args.ChannelUri.ToString());
await RegisterForMessageNotificationsAsync();
};
}
public async Task RegisterForMessageNotificationsAsync()
{
using (var client = GetNewHttpClient(true))
{
// Get the info that we need to request registration.
var installationId = LocalStorageManager.GetInstallationId(); // a new Guid
var registration = new Dictionary<string, string>()
{
{"platform", "windows"},
{"instId", installationId},
{"channelUri", _channel.ChannelUri.ToString()}
};
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(ApiUrl + "api/Register/RegisterForNotifications"));
request.Content = new StringContent(JsonConvert.SerializeObject(registration), Encoding.UTF8, "application/json");
string message;
try
{
HttpResponseMessage response = await client.SendAsync(request);
message = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
message = ex.Message;
}
_registrationId = message;
}
}
Any help would be greatly appriciated as I have been stuck on this now for days! I know this is a lot of code to paste up here but it is all relevant.
Thanks,
EDIT: The SubscribeToService() method is called when the user logs in and authenticates with the WebAPI. The method is here;
public async Task<User> SendSubmitLogonAsync(LogonObject lo)
{
_logonObject = lo;
using (var client = GetNewHttpClient(false))
{
var logonString = String.Format("grant_type=password&username={0}&password={1}", lo.username, lo.password);
var sc = new StringContent(logonString, Encoding.UTF8);
var response = await client.PostAsync("Token", sc);
if (response.IsSuccessStatusCode)
{
_logonResponse = await response.Content.ReadAsAsync<TokenResponseModel>();
var userInfo = await GetUserInfoAsync();
if (_channel == null)
SubscribeToService();
else
await RegisterForMessageNotificationsAsync();
return userInfo;
}
// ...
}
}
I have solved the issue. There are tons of fairly poorly organised howto's for azure notification hubs and only one of them has this note toward the bottom;
NOTE:
You will not receive the notification when you are still in the app.
To receive a toast notification while the app is active, you must
handle the ShellToastNotificationReceived event.
This is why I was experiencing intermittent results, as i assumed you would still get a notification if you were in the app. And this little note is pretty well hidden.
Have you used proper tag / tag expressions while register/send the message. Also, Where are you storing the id back from the notification hub. It should be used when you update the channel uri (it will expire).
I would suggest to start from scratch.
Ref: http://msdn.microsoft.com/en-us/library/dn530749.aspx

Resources