using Notifications.Wpf;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
using Tango.Logging;
using Tango.Settings;
namespace Tango.StubsUtils.Service.UI
{
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
private static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F0STUBSUTI}");
private WpfGlobalExceptionTrapper exceptionTrapper;
private LogManager LogManager = LogManager.Default;
private HashSet _ignoredGlobalExceptions;
public App() : base()
{
_ignoredGlobalExceptions = new HashSet();
}
protected override void OnStartup(StartupEventArgs e)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
//This is the first instance. Do nothing...
mutex.ReleaseMutex();
}
else
{
MessageBox.Show("Tango Stubs Service is already running.");
Environment.Exit(0);
}
//Set culture info.
var enUSCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = enUSCulture;
Thread.CurrentThread.CurrentUICulture = enUSCulture;
CultureInfo.DefaultThreadCurrentCulture = enUSCulture;
CultureInfo.DefaultThreadCurrentUICulture = enUSCulture;
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
base.OnStartup(e);
exceptionTrapper = new WpfGlobalExceptionTrapper();
exceptionTrapper.Initialize(this);
exceptionTrapper.ApplicationCrashed += ExceptionTrapper_ApplicationCrashed;
ServiceUISettings settings = SettingsManager.Default.GetOrCreate();
settings.Save();
}
private void ExceptionTrapper_ApplicationCrashed(object sender, ApplicationCrashedEventArgs e)
{
e.TryRecover = true;
List ignoredExceptions = new List()
{
"FocusVisualStyle",
"ThreadAbortException",
"A Task's exception(s) were not observed",
"The calling thread must be STA, because many UI components require this."
};
String exceptionString = e.Exception.ToStringSafe();
if (ignoredExceptions.Exists(x => exceptionString.Contains(x)))
{
return;
}
LogManager.Log(e.Exception, LogCategory.Critical, "Unexpected Application Error.");
Application.Current.Dispatcher.Invoke(() =>
{
try
{
LogManager.Log("Trying to notify the user about the crash...");
NotificationManager notification = new NotificationManager();
notification.Show(new NotificationContent()
{
Title = "Tango Stubs Service",
Message = $"Unexpected Application Error",
Type = NotificationType.Error
});
}
catch (Exception ex)
{
LogManager.Log(ex, "Error using the notification provider for notifying about application crash.");
}
});
}
}
}