Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Created January 20, 2015 20:44
Show Gist options
  • Select an option

  • Save nozzlegear/4cc6c8477fd3537caa67 to your computer and use it in GitHub Desktop.

Select an option

Save nozzlegear/4cc6c8477fd3537caa67 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.ApplicationModel.Background;
using ButterflyCore;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
namespace Background_Tasks
{
public sealed class SourceCheckerTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
//Use .GetDeferral to prevent race conditions where the task finishes before async code completes.
var deferral = taskInstance.GetDeferral();
var core = new Client();
var localSettings = ApplicationData.Current.LocalSettings;
//Query the YouTube API for the latest video
var query = await core.GetYouTubeUploads(1);
//Ensure it was successful and that it contains data
if (query.Success && query.Data?.data?.items != null)
{
//Get id of last checked video from app's local settings
var lastVideoId = localSettings.Values["LastVideoId"] as string;
//Get the latest video from the query
var latestVideo = query.Data.data.items.FirstOrDefault();
//If lastVideoId and latestVideo.id do not match, the returned video is new
if (lastVideoId?.ToLower() != latestVideo?.id?.ToLower())
{
//Show notification
try
{
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);
//Set toast image
((XmlElement)xml.GetElementsByTagName("image")[0]).SetAttribute("src", latestVideo.thumbnail.sqDefault);
//Set toast text
xml.GetElementsByTagName("text")[0].AppendChild(xml.CreateTextNode("Jesse Cox has uploaded a new video!"));
//Show toast
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(xml));
}
catch (Exception e)
{
//Do nothing. No way to warn user
}
//Store new video's id
localSettings.Values["LastVideoId"] = latestVideo.id;
}
}
//Complete the task after all async code is finished.
deferral.Complete();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment