codeMonkey
codeMonkey

Reputation: 4805

UWP Toast Notification debugging in Visual Studio - no toast displaying, "Returned with error code 0x0"

I have a background task that is supposed to open a toast message, à la: ToastNotificationManager.CreateToastNotifier().Show(toast);. My code executes fine, no errors are thrown, nothing hangs -- but also, no toast message appears.

I checked the Event Viewer logs, and they say this:

An instance of the background task with entry point BG.ToastBackgroundTask running for user [me] in session [sesh] returned with error code 0x0.

I have looked all over to see what this error code might mean but found nothing.

Here's my code:

public sealed class ToastBackgroundTask : IBackgroundTask
{
    private BackgroundTaskDeferral _deferral;

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        var cancelToken = new System.Threading.CancellationTokenSource();
        taskInstance.Canceled += (s, e) =>
            {
                cancelToken.Cancel();
                cancelToken.Dispose();
            };

        taskInstance.Task.Completed += Task_Completed;

        _deferral = taskInstance.GetDeferral();
        try
        {
            await SendNotificationAsync();
        }
        finally { _deferral.Complete(); }

    }

    public static async void Register()
    {
        var isRegistered = BackgroundTaskRegistration.AllTasks.Values.Any(x => x.Name == nameof(ToastBackgroundTask));
        if (isRegistered) return;

        var accessStatus = await BackgroundExecutionManager.RequestAccessAsync();
        if (accessStatus == BackgroundAccessStatus.DeniedByUser || accessStatus == BackgroundAccessStatus.DeniedBySystemPolicy) return;

        var builder = new BackgroundTaskBuilder
        {
            Name = nameof(ToastBackgroundTask),
            TaskEntryPoint = $"{nameof(MyNameSpace)}.{nameof(BG)}.{nameof(ToastBackgroundTask)}"
        };

        builder.SetTrigger(new TimeTrigger(120, false));

        var task = builder.Register();
    }

    private static void Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
    {
        try
        {
            args.CheckResult();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    private Task SendNotificationAsync()
    {
        var service = new ToastService();
        service.CreateToast(new ToastViewModel { Title = "Title", Text = "Text", ImagePath = "", Id = 3 });
        return Task.CompletedTask;
    }        
}

If I run CheckResult() on the completed task, no errors are thrown. Argh! Does anyone know (a) what this Event Viewer log error means, or (b) why my toast isn't showing up?

Here's my Toast code too in case it helps:

public class ToastService
{
    public void CreateToast(ToastViewModel model)
    {
        var visual = new ToastVisual()
        {
            BindingGeneric = new ToastBindingGeneric()
            {
                Children =
                {
                    new AdaptiveText() { Text = model.Title },
                    new AdaptiveText() { Text = model.Text }
                },
                Attribution = new ToastGenericAttributionText() { Text = "Via Me" }
            }
        };

        var tContent = new ToastContent()
        {
            Visual = visual,
            ActivationType = ToastActivationType.Background,
            Scenario = ToastScenario.Reminder
        };

        var toast = new ToastNotification(tContent.GetXml())
        {
            ExpirationTime = DateTime.Now.AddDays(model.Expiration)
        };
        toast.Failed += (o, args) => {
            var message = args.ErrorCode;
        };

        ToastNotificationManager.CreateToastNotifier().Show(toast);
    }
}

Upvotes: 1

Views: 641

Answers (1)

Sunteen Wu
Sunteen Wu

Reputation: 10627

Does anyone know (a) what this Event Viewer log error means, or (b) why my toast isn't showing up?

The above event log showed on my side is information level, not error level. The reason for the toast isn't showing up should be that you setting the ExpirationTime property for the ToastNotification. This property is for:

Gets or sets the time after which a toast notification should not be displayed.

So that if the model.Expiration equals to 0, the toast will not show from now. Ensure the expiration time later than now should work.

var toast = new ToastNotification(tContentxml)
{
   ExpirationTime = DateTime.Now.AddDays(1)
};

Otherwise your code snippet can work will on my side. If you still have issues, you can provide a minimal reproduced project to let us have a testing.

Upvotes: 1

Related Questions