Files
win8phoneApp/CampusAppWP8/CampusAppWP8ScheduledTaskAgent/ScheduledAgent.cs
2013-10-18 12:32:25 +02:00

426 lines
16 KiB
C#

//-----------------------------------------------------------------------
// <copyright file="ScheduledAgent.cs" company="BTU/IIT">
// The MIT License (MIT). Copyright (c) 2013 BTU/IIT.
// </copyright>
// <author>Stubbfel</author>
// <date>15.10.2013</date>
// <summary>Implements the scheduled agent class</summary>
//-----------------------------------------------------------------------
namespace CampusAppWP8ScheduledTaskAgent
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using CampusAppWP8ScheduledTaskAgent.Resources;
using CampusAppWP8ScheduledTaskAgent.Utility;
using CampusAppWPortalLib8.Model.Mensa;
using CampusAppWPortalLib8.Model.RSS;
using CampusAppWPortalLib8.Utility;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
/// <summary> Class for agent of the BackgroundTask. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <seealso cref="T:Microsoft.Phone.Scheduler.ScheduledTaskAgent"/>
public class ScheduledAgent : ScheduledTaskAgent
{
#region Member
/// <summary> Model for the mensa feed. </summary>
private MenuWeekModel mensaModel;
/// <summary> Model for the event feed. </summary>
private RSSViewModel eventModel;
/// <summary> Model for the news feed. </summary>
private RSSViewModel newsModel;
/// <summary> Variable for the running feeds. </summary>
private int runningFeeds;
#endregion
#region Constructor
/// <summary> Initializes static members of the <see cref="ScheduledAgent" /> class. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
static ScheduledAgent()
{
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
#endregion
#region Method
#region protected
/// <summary> override OnInvoke. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <seealso cref="M:Microsoft.Phone.Scheduler.ScheduledTaskAgent.OnInvoke(ScheduledTask)"/>
protected override void OnInvoke(ScheduledTask task)
{
int notRunningFeeds = 0;
this.runningFeeds = 0;
ShellTile tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathNews_NewsIndexPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathNews_NewsIndexPage))
{
this.runningFeeds++;
this.HandleNewsTask(task);
}
else
{
notRunningFeeds++;
}
tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathMensa_MensaPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathMensa_MensaPage))
{
this.runningFeeds++;
this.HandleMensaTask(task);
}
else
{
notRunningFeeds++;
}
tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathEvents_EventsIndexPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathEvents_EventsIndexPage))
{
this.runningFeeds++;
this.HandleEventTask(task);
}
else
{
notRunningFeeds++;
}
if (notRunningFeeds == 3)
{
BackgroundTasks.StopPerodicTask(Constants.BackgroundTask_BTUCampusApp);
}
}
#endregion
#region private
/// <summary> Method handle UnhandledException. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="sender"> sender of Exception. </param>
/// <param name="e"> Exception Args. </param>
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
/// <summary> Method handle the EventBackgroundTask. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="task"> the eventTask. </param>
private void HandleEventTask(ScheduledTask task)
{
if (this.eventModel == null || !this.CheckRssIsUpToDate(this.eventModel.CreateTime))
{
HttpRequest api = new HttpRequest();
Uri url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlEvents_Addr, UriKind.Absolute);
api.HttpGet(url, this.GetEventIsReady);
}
else
{
this.runningFeeds--;
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> Method handle the NewsBackgroundTask. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="task"> the newsTask. </param>
private void HandleNewsTask(ScheduledTask task)
{
if (this.newsModel == null || !this.CheckRssIsUpToDate(this.newsModel.CreateTime))
{
HttpRequest api = new HttpRequest();
Uri url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlNews_Addr, UriKind.Absolute);
api.HttpGet(url, this.GetNewsIsReady);
}
else
{
this.runningFeeds--;
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> ResponseHandler for the EventFeed. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="sender"> sender of the Event. </param>
/// <param name="arg"> Event Args. </param>
private void GetEventIsReady(object sender, System.Net.DownloadStringCompletedEventArgs arg)
{
if (arg.Result != null)
{
this.eventModel = XmlManager.DeserializationToModel<RSSViewModel>(arg.Result, CampusAppWPortalLib8.Resources.Constants.XMLRootElementName);
this.eventModel.Channel[0].OrderByDate();
this.UpdateEventTile();
}
else
{
this.runningFeeds--;
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> ResponseHandler for the NewsFeed. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="sender"> sender of the Event. </param>
/// <param name="arg"> Event Args. </param>
private void GetNewsIsReady(object sender, System.Net.DownloadStringCompletedEventArgs arg)
{
if (arg.Result != null)
{
this.newsModel = XmlManager.DeserializationToModel<RSSViewModel>(arg.Result, CampusAppWPortalLib8.Resources.Constants.XMLRootElementName);
this.newsModel.Channel[0].OrderByDate();
this.UpdateNewsTile();
}
else
{
this.runningFeeds--;
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> Method update the NewsTile. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
private void UpdateNewsTile()
{
ShellTile tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathNews_NewsIndexPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathNews_NewsIndexPage))
{
IconicTileData data = new IconicTileData();
Random random = new Random();
RSSModel item = this.newsModel.Channel[0].Item.FirstOrDefault();
if (item != null)
{
data.WideContent1 = item.Date;
data.WideContent2 = DefaultStringManager.ToShortString(item.Title, 40, "...");
data.WideContent3 = DefaultStringManager.ToShortString(item.Text, 40, "...");
tileToFind.Update(data);
}
this.runningFeeds--;
}
if (this.runningFeeds == 0)
{
this.NotifyComplete();
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> Method update the EventTile. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
private void UpdateEventTile()
{
ShellTile tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathEvents_EventsIndexPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathEvents_EventsIndexPage))
{
IconicTileData data = new IconicTileData();
Random random = new Random();
RSSModel item = this.eventModel.Channel[0].Item.FirstOrDefault();
if (item != null)
{
data.WideContent1 = item.Date;
data.WideContent2 = DefaultStringManager.ToShortString(item.Title, 40, "...");
data.WideContent3 = DefaultStringManager.ToShortString(item.Text, 40, "...");
tileToFind.Update(data);
}
this.runningFeeds--;
}
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
/// <summary> Determine the correct MensaFeed/Url. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="mensaTaskDesc"> the Description of the MensaTask. </param>
/// <returns> Url of a mensa, which is set is in the UserProfile. </returns>
private Uri CalcMensaUrl(string mensaTaskDesc)
{
Uri url;
char feedNumber = mensaTaskDesc[mensaTaskDesc.Length - 1];
switch (feedNumber)
{
case '1':
url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlMensa_Week_CBMain, UriKind.Absolute);
break;
case '2':
url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlMensa_Week_CBSouth, UriKind.Absolute);
break;
case '3':
url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlMensa_Week_SBFMain, UriKind.Absolute);
break;
case '4':
url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlMensa_Week_CBMain, UriKind.Absolute);
break;
default:
url = new Uri(CampusAppWPortalLib8.Resources.Constants.UrlMensa_Week_CBMain, UriKind.Absolute);
break;
}
return url;
}
/// <summary> Method handle the MensaBackgroundTask. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="task"> the newsTask. </param>
private void HandleMensaTask(ScheduledTask task)
{
if (this.mensaModel == null || !this.CheckMensaIsUpToDate(this.mensaModel.CreateTime))
{
HttpRequest api = new HttpRequest();
Uri url = this.CalcMensaUrl(task.Description);
api.HttpGet(url, this.GetMensaIsReady);
}
else
{
this.UpdateMensaTile();
}
}
/// <summary> ResponseHandler for the MensaFeed. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="sender"> sender of the Event. </param>
/// <param name="arg"> Event Args. </param>
private void GetMensaIsReady(object sender, System.Net.DownloadStringCompletedEventArgs arg)
{
if (arg.Result != null)
{
this.mensaModel = XmlManager.DeserializationToModel<MenuWeekModel>(arg.Result, CampusAppWPortalLib8.Resources.Constants.XMLRootElementName);
this.UpdateMensaTile();
}
else
{
this.runningFeeds--;
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
}
/// <summary> Method update the NewsTile. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
private void UpdateMensaTile()
{
ShellTile tileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathMensa_MensaPage));
if (tileToFind != null && tileToFind.NavigationUri.ToString().Contains(CampusAppWPortalLib8.Resources.Constants.PathMensa_MensaPage))
{
IconicTileData data = new IconicTileData();
DateTime now = DateTime.Now;
int dayIndex = (int)DateTime.Now.DayOfWeek;
data.WideContent1 = CultureInfo.CurrentCulture.DateTimeFormat.DayNames[dayIndex];
data.WideContent2 = now.Date.ToShortDateString();
if (dayIndex == 0 || dayIndex > this.mensaModel.Menus.Count)
{
data.WideContent3 = AppResources.MensaApp_CloseMensa;
}
else
{
// correct index (week sart with monday not sunday
dayIndex--;
int mealCount = this.mensaModel.Menus[dayIndex].Meals.Count;
if (mealCount < 1)
{
data.WideContent3 = AppResources.MensaApp_CloseMensa;
}
else
{
Random random = new Random();
int randomNumber = random.Next(0, mealCount);
MealModel meal = this.mensaModel.Menus[dayIndex].Meals[randomNumber];
data.WideContent3 = meal.MealName + ": " + DefaultStringManager.ToShortString(meal.MealDesc, 30, "...");
// data.Count = this.mensaModel.Menus[dayIndex].Meals.Count;
}
}
tileToFind.Update(data);
this.runningFeeds--;
}
if (this.runningFeeds == 0)
{
this.NotifyComplete();
}
}
/// <summary> Check if the model of the mensa is up-to-date. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="lastModified"> Date of the last modification. </param>
/// <returns> true, if it is up-to-date, otherwise false. </returns>
private bool CheckMensaIsUpToDate(DateTime lastModified)
{
int diff = lastModified.CompareTo(MenuWeekModel.CalcFirstWeekDay());
if (diff < 0)
{
return false;
}
return true;
}
/// <summary> Check if the model of the RSS feed is up-to-date. </summary>
/// <remarks> Stubbfel, 15.10.2013. </remarks>
/// <param name="lastModified"> Date of the last modification. </param>
/// <returns> true, if it is up-to-date, otherwise false. </returns>
private bool CheckRssIsUpToDate(DateTime lastModified)
{
int diff = lastModified.CompareTo(DateTime.Now.AddDays(1));
if (diff < 0)
{
return false;
}
return true;
}
#endregion
#endregion
}
}